| | Stumble It! | Add to Mixx! | | diigo it | | Slashdot |

Thursday, June 18, 2009

JavaScript IP Address Validation

In a couple projects that I've been working on lately, I've had to collect user input that included IP addresses. For those of you who don't work with IP addresses on a regular basis, it's really easy to get into a rhythm while typing them and mistype the address. This kind of typo can be immensely frustrating as it's easy to overlook after typing 20 dozen or so.

So here's a simple JavaScript function to validate the user entered an actual, valid IP address. Of course it won't validate that your user typed the CORRECT IP address, just that they did, in fact, type a valid IP.
function isIP(obj) {
var ary = obj.value.split(".");
var ip = true;

for (var i in ary) { ip = (!ary[i].match(/^\d{1,3}$/) || (Number(ary[i]) > 255)) ? false : ip; }
ip = (ary.length != 4) ? false : ip;

if (!ip) { // the value is NOT a valid IP address
obj.style.background = "red";
obj.value = "Not a valid IP address";
obj.select();
} else { obj.style.background = ""; } // the value IS a valid IP address
}

The best way that I've found to implement this code is to add an "onBlur" call in the <input ...> tag like so:
<input type="text" id="ip" onBlur="isIP(this)" />

Enjoy!

2 comments:

Chlastani said...

Little modification:
for (var i in ary) { ip = (!ary[i].match(/\d{1,3}/) || (Number(ary[i]) > 255)) || !Number(ary[i]) ? false : ip; }


(before this improvement was valid IP like 9aaaaaaaaa0.183.12.18)

Thank you for this code

Ben said...

Chlastani,

Good catch! I missed that one. I tried to figure out how to check for trailing alpha characters without having to add another condition, but sadly my regex skills don't reach that far yet.

Thanks for the code!

-Ben