Solved

data validation for an IP address by Java Script

Posted on 2007-03-26
14
285 Views
Last Modified: 2008-01-09
I develop JS code for verifying an IP address. Here is my jS code

function verifyIP (IPvalue) {
errorString = "";
theName = "IPaddress";

var ipPattern = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
var ipArray = IPvalue.match(ipPattern);

if (IPvalue == "0.0.0.0")
errorString = errorString + theName + ': '+IPvalue+' is a special IP address and cannot be used here.';
else if (IPvalue == "255.255.255.255")
errorString = errorString + theName + ': '+IPvalue+' is a special IP address and cannot be used here.';
if (ipArray == null)
errorString = errorString + theName + ': '+IPvalue+' is not a valid IP address.';


else {
for (i = 0; i < 4; i++) {
thisSegment = ipArray[i];
if (thisSegment > 255) {
errorString = errorString + theName + ': '+IPvalue+' is not a valid IP address.';


i = 4;
}
if ((i == 0) && (thisSegment > 255)) {
errorString = errorString + theName + ': '+IPvalue+' is a special IP address and cannot be used here.';
i = 4;
      }
   }
}
extensionLength = 3;
if (errorString == "")
alert ("That is a valid IP address.");
else
alert (errorString);
}

function ValidateForm(){
      var dt=document.IP_to_MAC.BegDate
        var dt2=document.IP_to_MAC.EndDate
       var dt3= document.IP_to_MAC.IPvalue
         
      if (isDate(dt.value)==false)
        {
            dt.focus()
            return false
         }
         else if (isDate(dt2.value)==false)
         {
                dt2.focus()
            return false
      }
       
       else if  (verifyIP(IPvalue.value)==false)
        {
        alert("Invalid IP format.\n Only correct IP are allowed.");
        dt3.focus()
        return false
        }
    return true
 }
 
 
 function ValidateIntlNumber(fld) {
     if (fld.value.match(/[^0-9]/)) {
     
          alert ('Only numbers are permitted');
          // Un comment the next line is you want to remove the non-numbers automatically
          fld.value=fld.value.replace(/[^0-9]/g,'');
     }
}

 
 
</script>    <form name="IP_to_MAC" action="<portlet:actionURL/>" method="post" onSubmit="return ValidateForm()" >
   <input type='submit' value="Search" name="Search_MAC" onClick="verifyIP(IPvalue.value)";  >
           
</form>



  Search for IP Address: <input id="txtIP" type="text" name="IPvalue" size="15" maxlength="25" onkeyup="toggleVisibility(1);" >

Now I am running into a problem that when I input a wrong IP, then click on search button, it did pop up a message telling me wrong IP. But, then the page did not stay but automatically throw out an exception. I want it stayed in the same page if it's a wrong IP input. How to modify my above code so that when an wrong IP message popped up, then stay in the same page, not to go to next page or throw out an exception
0
Comment
Question by:wasabi3689
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 4
  • 3
14 Comments
 
LVL 29

Expert Comment

by:rdivilbiss
ID: 18796621
0
 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 18796657
It would seem like a return false is being ignored.  I'm a little puzzled by the script though.  Why do you call verifyIP with the Submit button's onclick and then run it with the ValidateForm function?

Which error message do you get?  I think the problem is basically the ValidateForm not getting "false" returned when it calls verifyIP.  I will need to look at the code in detail to find out for sure.  I suggest cleaning up the script so the IP is only checked once.

Let me know if you have a question or need more information.

bol
0
 
LVL 29

Expert Comment

by:rdivilbiss
ID: 18796706
Strange function, try this....and do what bol said, re: submit:

<input type='submit' value="Search" name="Search_MAC">

function ValidateForm(){
      var dt=document.IP_to_MAC.BegDate
      var dt2=document.IP_to_MAC.EndDate
      var dt3= document.IP_to_MAC.IPvalue
   
      if (isDate(dt.value)==false) {
            dt.focus();
            return false;
      }
      if (isDate(dt2.value)==false) {
          dt2.focus();
          return false;
      }
      if (verifyIP(IPvalue.value)==false) {
          alert("Invalid IP format.\n Only correct IP are allowed.");
          dt3.focus();
          return false;
      }
      return true;
 }

And my page above only allows valid IP's.  Much simpler that your routine.
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 18796738
I think a fix is as simple as changing the end of the verifyIP function.  I haven't looked at your code in details still so I may be missing something but the block below (showing changes) should fix it.

      if (errorString == "") {
            alert ("That is a valid IP address.");
            return true;
      } else {
            alert (errorString);
            return false;
      }

I still recommend that you don't call the verifyIP function with the submit button's onclick event and just let it run as part of verifyForm.

Let me know if you have a question.

bol
0
 

Author Comment

by:wasabi3689
ID: 18802780
Hi

I use the code from the link above

http://www.rodsdot.com/ee/IP-Address-Validation.asp

But I come up a same problem. When input a wrong Ip, it did pop up an error message then automatically move to another page when I click “ok” button. I want it stay in the page, not moving if it’s a wrong IP. How to fix it?

Here is my JS code

In view.jsp
<script type="text/javascript">

function validate(f) {
    f.className="";
   // var dt3= document.IP_to_MAC.IPvalue;
    var RegExPattern = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
    if ((f.value.match(RegExPattern)) && (f.value!='')) {
       // alert('good');
        document.getElementById("msg").innerHTML = "Valid IP";
    }else{
        alert('bad IP');
        //dt3.focus();
        f.className = "fieldError";
        document.getElementById("msg").innerHTML = "Try Again";
    }
}

</script>


    <form name="IP_to_MAC" action="<portlet:actionURL/>" method="post" onSubmit="return ValidateForm()" >
       
               
               
            <div style="padding-top:5px;padding-bottom:5px;" id="ICC">
               
                        Search for MAC Address: <input id="txtMAC" type="text" name="MACAddress" size="17" maxlength="25" onkeyup="toggleVisibility(2);" value ="00:0A:95:77:C3:CE">
 
                      - or -
                        Search for IP Address: <input id="txtIP" type="text" name="IPvalue" size="15" maxlength="25" onkeyup="toggleVisibility(1);" >

   <input type='submit' value="Search" name="Search_MAC" onclick="validate(document.getElementById('txtIP'));"  >
           
</form>

In my java code

…….
else if ( MySearch_MAC!= null)
         {
                PortletRequestDispatcher dispatcher =
                        getPortletContext().getRequestDispatcher("/IPMACSearchResult.jsp");
                dispatcher.include(request, response);
           
           
         }    
0
 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 18803586
To not have a form submit you need to use "return functionName" in the event (i.e. onclick in a Submit button or onsubmit in the Form tag).  Then in the function you need to return true or return false.  I will work on the new code to show you.

bol
0
 
LVL 54

Accepted Solution

by:
b0lsc0tt earned 50 total points
ID: 18803601
This is an example of how to do it using the code you just posted.

<script type="text/javascript">

function validate(f) {
    f.className="";
   // var dt3= document.IP_to_MAC.IPvalue;
    var RegExPattern = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
    if ((f.value.match(RegExPattern)) && (f.value!='')) {
       // alert('good');
        document.getElementById("msg").innerHTML = "Valid IP";
        return true;
    }else{
        alert('bad IP');
        //dt3.focus();
        f.className = "fieldError";
        document.getElementById("msg").innerHTML = "Try Again";
        return false;
    }
}

</script>


    <form name="IP_to_MAC" action="<portlet:actionURL/>" method="post" onSubmit="return ValidateForm()" >
       
               
               
            <div style="padding-top:5px;padding-bottom:5px;" id="ICC">
               
                        Search for MAC Address: <input id="txtMAC" type="text" name="MACAddress" size="17" maxlength="25" onkeyup="toggleVisibility(2);" value ="00:0A:95:77:C3:CE">
 
                      - or -
                        Search for IP Address: <input id="txtIP" type="text" name="IPvalue" size="15" maxlength="25" onkeyup="toggleVisibility(1);" >

   <input type='submit' value="Search" name="Search_MAC" onclick="return validate(document.getElementById('txtIP'));"  >
           
</form>
0
 

Author Comment

by:wasabi3689
ID: 18803775
I still go to next page even I input a wrong IP by your code above. It can not allow me to pause in the page but moving to next page
0
 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 18803877
I see now that you still call ValidateForm form the onsubmit event.  Did you put my change into that code?  If not then that may be the problem.  Please show the current code for both functions and for the form (all of the form).

bol
0
 

Author Comment

by:wasabi3689
ID: 18803934
Here it 's the line I modify. it works

document.getElementById("txtIP").innerHTML = "Try Again";
0
 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 18803979
>> it works

Does that mean the problem is solved (i.e. the form isn't submitted when there is an error) or just you can get that line to print "Try Again" on the page?  Since you just provided that line I will assume it is working and I'm glad to hear it.  Let us know if you have some question about this still.  Don't forget that Rdivilbiss provided the code that improved your validation.  You got a good deal for 50 points. :D

bol
0
 

Author Comment

by:wasabi3689
ID: 18804721
Hi, you 've got 50 points. Do you want another 50 points. I just post another simliar question. This time I need a sample JS code for MAC address validation
0
 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 18804764
I look at that question and see if I can help.

I noticed you were somewhat new and just wanted to make sure you knew you could split points if more than one comment helped.  I'm not saying you did anything wrong here but just in case you didn't know.  Let me know if you need more info on this. :)

Thanks for the fun question, the grade and the points.  I'm glad I could help.

bol
0
 
LVL 29

Expert Comment

by:rdivilbiss
ID: 18804795
I do not care about the points, due to my experience here and bols being careful to credit my contribution, but you want to take his advice and not offend other experts if you don't award the person who wrote the code, which often they won't do for you for 50 points.  Bols was available this afternoon, I wasn't.  Glad you got it worked out, but the problem was never with my code.  
0

Featured Post

What Is Transaction Monitoring and who needs it?

Synthetic Transaction Monitoring that you need for the day to day, which ensures your business website keeps running optimally, and that there is no downtime to impact your customer experience.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: DanRollins
This article describes a JavaScript program that creates a maze made of hexagonal cells.  In Part 2 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7850-Hex-Maze-Part-2.html), we'll extend the program by adding a depth-…
Having worked on larger scale sites, we found out that you are bound to look at more scalable solutions to integrating widgets, code snippets or complete applications and mesh them into functional sites, in any given composition. To share some of…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

724 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question