function isValidIP(ip) {
    var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
    return reg.test(ip);
}

主要是ip的正则表达式。

应用场景:

<!DOCTYPE html>
<html>
<head>
<title>ip校验</title>
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script>
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>
<script	src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script>
</head>
<body>
	<form class="cmxform" id="commentForm" method="get" action="">
		<fieldset>
			<legend>输入您的IP</legend>
			<p>
				<label for="ip">ip</label> <input id="cname" name="ip" type="text"	required>
			</p>
			<p>
				<input class="submit" type="submit" value="Submit">
			</p>
		</fieldset>
	</form>
</body>
</html>


<script>
$("#commentForm").validate({
    focusCleanup: true,
    rules:{
    	ip:{
            isValidIP:true,
        }
    }
});

$(function() {
   jQuery.validator.addMethod("isValidIP", function (value, element){
        return this.optional(element) || isValidIP(value);
    },"请输入正确的IP地址");
        	 
   function isValidIP(ip) {
	    var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
	    return reg.test(ip);
   }

});
</script>


js验证ip地址_js验证ip地址

这种方式是自定义jquery-validate的方法,只要你的逻辑,返回true或者false即可,针对不同业务,你都可以搞定前端校验。

欢迎加入康哥IT粉丝交流QQ群833249482