如何用js来验证IP地址的有效性呢?可以借助js的正则来实现。
1,html部分
复制代码 代码示例:
<html lang="en">
<head>
<meta charset="utf-8">
<title>
javascript正则验证IP地址-www.jb200.com</title>
<link rel='stylesheet' href='form-style.css' type='text/css' />
</head><br><body onload='document.form1.text1.focus()'>
<div class="mail">
<h2>请输入IP地址并提交</h2>
<form name="form1" action="#">
<ul>
<li><input type='text' name='text1'/></li>
<li> </li>
<li class="submit"><input type="submit" name="submit" value="Submit" onclick="ValidateIPaddress(document.form1.text1)"/></li>
<li> </li>
</ul>
</form>
</div>
<script src="ipaddress-validation.js"></script>
</body>
</html>
2,js代码-ipaddress-validation.js
复制代码 代码示例:
function ValidateIPaddress(inputText)
{
var ipformat = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
if(inputText.value.match(ipformat))
{
document.form1.text1.focus();
return true;
}
else
{
alert("You have entered an invalid IP address!");
document.form1.text1.focus();<br>return false;
}
}
3,css代码-form-style.css
复制代码 代码示例:
li {list-style-type: none;
font-size: 16pt;
}
.mail {
margin: auto;
padding-top: 10px;
padding-bottom: 10px;
width: 400px;
background : #D8F1F8;
border: 1px soild silver;
}
.mail h2 {
margin-left: 38px;
}
input {
font-size: 20pt;
}
input:focus, textarea:focus{
background-color: lightyellow;
}
input submit {
font-size: 12pt;
}
.rq {
color: #FF0000;
font-size: 10pt;
}
效果图例:
附,网友提供的验证IP地址的方法。
复制代码 代码示例:
<html>
<head>
<title>IP地址验证_www.jb200.com</title>
<script type='text/javascript'>
function validate( value ) {
var ipRE = new RegExp( '^d+.d+.d+.d+$' );
alert( ( ipRE.test( value ) ? '' : 'in' ) + 'valid' );
}
</script>
</head>
<body>
Address: <input type='text' onchange='validate(this.value)'>
</body>
</html>