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:
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
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
Post a Comment