data validation for an IP address by Java Script

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
wasabi3689Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

b0lsc0ttIT ManagerCommented:
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
rdivilbissCommented:
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
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

b0lsc0ttIT ManagerCommented:
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
wasabi3689Author Commented:
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
b0lsc0ttIT ManagerCommented:
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
b0lsc0ttIT ManagerCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
wasabi3689Author Commented:
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
b0lsc0ttIT ManagerCommented:
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
wasabi3689Author Commented:
Here it 's the line I modify. it works

document.getElementById("txtIP").innerHTML = "Try Again";
0
b0lsc0ttIT ManagerCommented:
>> 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
wasabi3689Author Commented:
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
b0lsc0ttIT ManagerCommented:
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
rdivilbissCommented:
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.