首页 > 代码库 > javaScript验证ip的合法性

javaScript验证ip的合法性

<script language=javascript>

function check(ipaddr)

{

var ipaddr=document.all.ip.value;

var re = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;

if (re.test(ipaddr))

{

//split into units with dots "."

var parts = ipaddr.split(".");

//if the first unit is zero

if (parseInt(parseFloat(parts[0])) == 0)

{

alert("错误");

return false;

}

if (parseInt(parseFloat(parts[3])) == 0)

{

alert("错误");

return false;

}

// if any part is greater than 255

for (var i=0; i<parts.length; i++)

{

if (parseInt(parseFloat(parts[i])) > 254)

{

alert("错误");

return false;

}

}

alert("正确");

return true;

} else

{

alert("错误");

return false;

}

}

</script>

<form name="all" type="post" action="">

<input type="text" name="ip">

<input type="button" value="tijiao" onclick="javascript:check()">

</form>

javaScript验证ip的合法性