为验证IP地址的合法性,特写了这样一个js脚本。
本函数接收一个IP地址作为输入参数,如果该字符串是一个有效的IP地址,则反回true,否则为false。
注意:此函数仅用于验证C类IP地址。
代码:
<script language="javascrit">
/**
* 验证 IP Address IPv4 *
*/
function fnValidateIPAddress(ipaddr) {
//此函数仅用于验证C类地址
//请根据自己的需要修改为验证其它类别的IP地址
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;
}
}
</script>