In one of my current project ( Front end for an ISM Device ), I’ve to validate IP Addresses using JavaScript.

And wrote this function fnValidateIPAddress

The function takes an IP Address as input string and returns either true if the input string is a valid IP Address or false if not. This function checks for the Class C IP Addresses only. This function can be changed further to validate different IP Classes.

/******* Validate IP Address IPv4 *********/
function fnValidateIPAddress(ipaddr) {
    //Remember, this function will validate only Class C IP.
    //change to other IP Classes as you need
    ipaddr = ipaddr.replace( /\s/g, "") //remove spaces for checking
    var re = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/; //regex. check for digits and in
                                          //all 4 quadrants of the IP
    if (re.test(ipaddr)) {
        //split into units with dots "."
        var parts = ipaddr.split(".");
        //if the first unit/quadrant of the IP is zero
        if (parseInt(parseFloat(parts[0])) == 0) {
            return false;
        }
        //if the fourth unit/quadrant of the IP is zero
        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])) > 255){
                return false;
            }
        }
        return true;
    } else {
        return false;
    }
}

What going on inside the function.

First stripping out any spaces in the input string
Then check if there are 4 quadrants in the input, becasue an IP (v4) will contain 4 quadrants 192.168.1.1
and all them are digits (numbers) only
If so then Check if the first or last quadrants are Zero.
If any of them is zero, then return false. The input string is not a valid IP Address (Class C IP Address)
Else check if any of the four quadrants/parts are greater than 255. If so return false. The input string is not a valid IP Address (Class C IP Address)

If none of the conditions fail, then the Input string (IP Address) is an valid IP Address.

Note:
Here am checking for Class C IP Address validation only. This can be further extended to check for other IP Classes.

For reference please visit

http://www.tcpipguide.com/free/t_IPClassfulAddressingOverviewandAddressClasses.htm

http://en.wikipedia.org/wiki/Classful_network

Let me know you comments.

Be Sociable, Share!