Validate/match IP address into a web form with Javascript

Posted on mercoledì 19 gennaio 2011 by Ivano Binetti

I have written this javascript function to validate an IP address (IPv4) and the netmask inside a html form:

function checkip() {
var ipaddress = document.getElementById("ip").value;
var subnet = document.getElementById("netmask").value;
var patt = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
var match = ipaddress.match(patt);
var match2 = subnet.match(patt);

if (ipaddress == "0.0.0.0") {
alert ("The IP Address field cannot be 0.0.0.0");
return false;
}

if (ipaddress == "255.255.255.255") {
alert ("The IP Address field cannot be 255.255.255.255");
return false;
}

if (match == null) {
alert ("Please review your IP Adrress!");
return false;
}

if (match2 == null) {
alert ("Please review your Subnet Mask!");
return false;
}

else {
document.getElementById("form1").submit();
window.close();
}
}

0 Responses to "Validate/match IP address into a web form with Javascript":