<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>表单验证</title>
</head>
<script type="text/javascript" src="jquery-validation-1.14.0/lib/jquery.js"></script>
<script type="text/javascript" src="jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>
<script type="text/javascript" src="jquery-validation-1.14.0/dist/localization/messages_zh.js"></script>
<script type="text/javascript" src="jquery-validation-1.14.0/dist/additional-methods.js"></script>
<style type="text/css">
p{margin:0;}
label.error{ color:red;font-size: 12px;text-indent: 2em;display: inline-block;background:url("./images/error.png") no-repeat 0 0;}
</style>
<body>
<div class="container">
<form id="infor_form" method="get">
<fieldset>
<legend>请输入您的姓名、邮箱和电话号码</legend>
<p>
<label for="name">姓名</label>
<input type="text" name="name" id="name" required>
</p>
<p>
<label for="mail">邮箱</label>
<input type="email" name="mail" id="mail" required>
</p>
<p>
<label for="tel">电话</label>
<input type="text" name="tel" id="tel" required>
</p>
<p>
<label for="password">密码</label>
<input type="text" name="password" id="password" required>
</p>
<p>
<label for="password1">再次输入密码</label>
<input type="text" name="password1" id="password1" required>
</p>
<p><input type="submit" class="submit" value="submit"></p>
</fieldset>
</form>
</div>
</body>
<script type="text/javascript">
$(function(){
$('#infor_form').validate({
rules:{
name:{
isChinaName:true,
minlength:2,
maxlength:10
},
tel:{
isTel:true
},
email: {
isMail: true
},
password:{
required:true,
minlength:3
},
password1:{
required:true,
minlength:3,
equalTo: "#password"
}
},
messages:{
name:{
isChinaName:"请输入一个合法的中文名",
},
tel:{
isTel:"请输一个正确的手机号码"
},
email:{
isMail:"请输入一个有效的邮箱地址"
},
password1:{
equalTo:"两次密码输入不一致"
}
},
errorPlacement: function(error, element) {
//error.appendTo(element.parent()); //显示在当前input的右侧
error.insertAfter(element.parent());//显示在p标签的下方
}
});
})
</script>
</html>
在此贴上我的笔记,望对大家有所帮助
我在additional-methods.js中自定义添加的代码为:
//手机号验证
jQuery.validator.addMethod("isTel", function(value, element) {
var tel = /^1[0-9]{10}$/;
return this.optional(element) || (tel.test(value));
}, "请正确填写您手机号码");
//邮箱地址
jQuery.validator.addMethod("isMail", function(value, element) {
var mail= /^(\w)+((\.|-)\w+)*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
return this.optional(element) || (mail.test(value));
}, "请输入一个有效的邮箱地址");
// 姓名验证
jQuery.validator.addMethod("isChinaName", function(value, element) {
var pattern= /^[\u4E00-\u9FA5A-Za-z]+$/;
return this.optional(element) || (pattern.test(value));
}, "请输入一个有效的中文名");
注意:自定义的方法要与原文件中方法保持一致,逗号隔开。
最后的效果就是: