Validate an IP Address (IP Version 4 - IPV4)





4
Date Submitted Fri. Aug. 4th, 2006 7:55 AM
Revision 1 of 1
Syntax Master sundaramkumar
Tags JavaScript
Comments 0 comments
This code snippet will validate an IP Address (IP v4).
return true if the ip address is valid. Else false.


/******* Validate IP Address IPv4 *********/
function fnValidateIPAddress(ipaddr) {
   var re = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
   if (re.test(ipaddr)) {
      //split into units with dots "."
      var parts = ipaddr.split(".");
      //if the first unit is zero
      if (parseInt(parseFloat(parts[0])) == 0) {
         return false;
      }
      if (parseInt(parseFloat(parts[3])) == 0) {
         return false;
      }
      //if any part is greater than 255
      for (var i=0; i<parts.length; i++) {
         if (parseInt(parseFloat(parts[i])) > 254){
                 return false;
         }
      }
      return true;
   } else {
      return false;
   }
}


 

Comments

There are currently no comments for this snippet.

Voting