jQuery Validate 插件为表单提供了强大的验证功能,让客户端表单验证变得更简单,同时提供了大量的定制选项,满足应用程序各种需求。该插件捆绑了一套有用的验证方法,包括 URL 和电子邮件验证,同时提供了一个用来编写用户自定义方法的 API。所有的捆绑方法默认使用英语作为错误信息,且已翻译成其他 37 种语言。
菜鸟教程: https://www.runoob.com/jquery/jquery-plugin-validate.html
github:https://github.com/jquery-validation/jquery-validation
参数参考:https://www.cnblogs.com/sandea/p/3660345.html
https://jqueryvalidation.org/documentation/
导入jquery.js,validate基于jquery
导入validate.js
页面加载成功后,对表单进行校验,$(“选择器”).validate();
<form action="" id="login">
必填: <input type="text" name="userName" id=""><br />
必填数字: <input type="password" name="pwd" id=""><br />
校验数字: <input type="password" name="repwd" id=""><br />
最小数字: <input type="text" name="minNum" id=""><br />
区间: <input type="text" name="range" id=""><br />
<input type="submit" value="提交">
</form>
<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>
//点击提交表单时触发下面事件
$.validator.setDefaults({
submitHandler: function () {
alert("提交事件!");
}
});
//对表单进行验证
$("#login").validate({
rules: {
//一个规则:字段的name属性:"校验器"
//多个规则: 字段的name属性:{校验器:"值", 校验器: "值"}
userName: "required", //必填
pwd: {
required: true, //必填
rangelength: [6, 15], //填入的长度为6-15
},
repwd: {
equalTo:"[name='pwd']"
},
minNum: {
min: 5 //最小值为5
},
range:{
range:[10,15]
}
},
messages: {
//字段的name属性: "提示信息",
//字段的name属性: {校验器: "提示信息", 校验器: "提示信息"}
userName: '请填入用户名',
pwd: {
required: '请填入密码',
rangelength: '密码长度为6-15位',
},
repwd: {
equalTo: "两次输入不一致"
},
minNum: {
min: "最小值为{0}" //{0}表示获取relus.minNum.min的值
},
range:{
range:$.validator.format("取值范围为{0}~{1}之间")
}
}
})
</script>
在使用验证插件jquery.validate.js 时候 ,同时使用 errorPlacement 和 success 方法时 会发现 无论验证成功和失败都会调用errorPlacement 方法。验证成功时,会先调用errorPlacement ,然后调用success方法,这样会导致验证正确输入时 先会显示错误 然后再正确 有个一瞬间的改变。。如果必须要用这个方法,你可以在errorPlacement 方法里面做出一个判断
unhighlight 方法是jquery.validate验证通过会调用的方法。
errorPlacement 方法是出现错误调用的方法
更详细的属性可以参考:https://www.cnblogs.com/sandea/p/3660345.html
属性 | 描述 | 取值 |
---|---|---|
debug | 开启调试模式。如果为true,表单不会提交,而且会在控制台显示一些错误消息(需要Firebug或者Firebug lite)。当要阻止表单默认提交事件,尝试去开启它。 | Boolean 默认:false |
errorClass:‘error’ | 验证失败时,向被验证的元素添加的class | String 默认:error |
validClass:‘success’ | 验证成功时,向被验证的元素添加的class | String 默认:valid |
errorElement:‘label’ | 用html元素类型创建错误消息的容器。默认的"label"有个优点就是能在错误消息与无效表单之间用for属性建立有意义的联系(一个常常使用的,而不管表单元素是什么的)。 | String 默认为’label’ |
wrapper:‘li’ | 用一个指定的元素将错误消息包围。与errorLabelContainer一起创建一个错误消息列表非常有用。 | String |
errorLabelContainer:$(“#ant ul”) | 错误消息标签的容器。 | Selector |
errorContainer: $(“#ant”) | 错误消息的容器。 | Selector |
rules | 校验规则 | Object |
messages | 自定义校验失败的提示信息 | Object |
errorPlacement: function(error, element) | 用户自定义错误标签的显示位置。第一个参数:一个作为jQuery对象的错误标签,第二个参数为:一个作为jQuery对象的未通过验证的表单元素。 | Callback |
submitHandler: function(form) | 当表单通过验证,提交表单。 | form: 被验证的表单 |
highlight: function(element, errorClass) | ||
invalidHandler: function(form, validator) | 当未通过验证的表单提交时,可以在该回调函数中处理一些事情。 | form: 被验证的表单 validator: 验证器,可以使用validator.numberOfInvalids()获取错误的个数 |
ignore: ‘break’ | 不验证class为break的元素 | String |
groups | 指定错误消息分组。一个组由一个任意的组名作为键,一个由空白符分割的表单元素name属性列表作为值。用errorPlacement定义组消息的存放位置。 | Option |
onsubmit | 提交时验证表单。当设置为false时,不进行表单验证,验证规则失效。 | boolean 不能取值为true,详情看下边 |
onfocusout | 焦点离开时验证(单选/复选按钮除外)。如果表单中没有输入任何内容,所有的规则将被跳过,除非该表单已经被标记为无效的。 | Boolean 不能取值为true,详情看下边 |
onkeyup | 当键盘按键弹起时验证。只要表单元素没有被标记成无效的,不会有反应。另外,所有的规则将在每次按键弹起时验证。 | Boolean 不能取值为true,详情看下边 |
onclick | 鼠标点击验证针对单选和复选按钮。 | Boolean 不能取值为true,详情看下边 |
focusInvalid | 当验证无效时,焦点跳到第一个无效的表单元素。当为false时,验证无效时,没有焦点响应。 | Boolean 默认:true |
focusCleanup | 如果为true,当表单得到焦点时,移除在该表单上的errorClass并隐藏所有错误消息。避免与focusInvalid一起使用。 | Boolean 默认:false |
meta | 如果想使用其它插件来使用元数据验证规则,得指定相应的元数据对象。 | String |
showErrors | 自 定义消息显示的句柄。该回调函数有两个参数,第一 个为errorMap,第二个参数为errorList,在validator对象的上下文中调用。参数只包含那些经过onblur/onkeyup验证 的表单元素,也有可能是单个元素。除此之外,你还可以用this.defaultShowErrors()触发默认的行为。 | callback |
success | 如果指定它,当验证通过时显示一个消息。如果是String类型的,则添加该样式到标签中,如果是一个回调函数,则将标签作为其唯一的参数。 | String,Callback |
highlight | 将未通过验证的表单元素设置高亮。 | Callback |
unhighlight | 与highlight操作相反 | Callback |
ignoreTitle | 设置它用来跳过错误消息对title属性的引用,避免Google工具栏引起的冲突。 | Boolean 默认false |
validate方法返回一个Validator对象,该对象具有一些公共方法,您可以使用这些方法以编程方式触发验证或更改表单的内容。验证器对象具有更多方法,但是仅此处记录的方法可供使用。
方法 | 描述 | 参数说明 |
---|---|---|
form() | 验证表格 | 无参数 |
element(element) | 验证单个元素,有效返回true,否则返回false | element :要验证的元素(必须在已验证的表单内) |
resetForm() | 重置此验证器控制的表单。 | 无参数 |
numberOfInvalids( errors ) | 返回无效字段的数量。 | errors是一个对象,输入名称和消息的一个或多个键/值对。实际用下来,参数貌似不管用 |
destroy() | 销毁该验证器实例,以释放资源并取消注册事件。 | 无参数 |
showErrors(errors) | 显示指定的消息。 | input 的 name 和消息的一个或多个键/值对。 |
//html: <input type="text" name="firstname">
var validator = $( "#myshowErrors" ).validate();
validator.showErrors({
"firstname": "I know that your firstname is Pete, Pete!"
});
参数:
form:可选,表示需要提交的表单
只修改一个表单的submit
$("#login").validate({ //只修改#login的提交事件
submitHandler: function (form) { //参数form可选
alert("login提交!"); //进行一系列处理
form.submit(); //提交表单
},
})
替换页面中多个表单的submit
//无论是提交form1还是form2都会触发下面的事件
$.validator.setDefaults({
submitHandler: function (form) {
alert("提交事件!");
form.submit();
}
});
$(function () {
$("#form1").validate();
$("#form2").validate();
});
为一个表单设置
$(function () {
$("#form1").validate({
debug: true,
});
});
页面中有多个表单都想设置为debug,可以设置为如下
$.validator.setDefaults({
debug: true
})
对form1中类为ignore的元素不验证
$("#form1").validate({
ignore: ".ignore" //不验证所有class为ignore的元素
})
页面中有多个表单时
$.validator.setDefaults({
ignore: ".ignore" //不验证所有class为ignore的元素
})
参数:
默认情况是:error.appendTo(element.parent());即把错误信息放在验证的元素后面。
<form method="get" class="cmxform" id="form1" action="">
<label for="user">用户名</label>
<input id="user" name="user" required minlength="3">
<button type="submit">提交</button>
</form>
<script>
$(function () {
$("#form1").validate({
errorPlacement: function (error, element){
//默认 $(element).parent().append(error);
//将错误信息放在label里面
$(element).closest("form").find("label[for='"+ $(element).attr('id') +"']").append(error)
},
errorElement: "span", //将错误信息使用span包裹,默认为label
errorClass: 'my-error', //错误信息添加my-error类
})
});
</script>
当success后跟一个函数时,没验证成功一个表单内的元素就会触发一次。
$("#form1").validate({
success: function (label){ //每验证成功一个触发一次
console.log("验证成功一个");
}
})
当success后跟字符串时,验证成功的元素添加该类
$("#form1").validate({
success:"valid", // 每验证成功一个就给该元素添加valid类
})
远程地址只能输出 “true” 或 “false”,不能有其他输出。
$form.validate({
rules: {
userName: {
required: true,
minlength: 3,
maxlength: 16,
remote: {
url: "check-user-name.php", //后台处理程序
type: "post", //数据发送方式
async: false, //是否为异步,默认为true,有时候不太管用,如果不管用,可以使用自定义方法,使用ajax来进行同步操作
cache:false,//是否缓存
dataType: "json",
data: { //要传递的数据
username: function () {
return $("#username").val();
}
}
},
dataFilter: function (data, type) { //接收服务器返回回来的数据
if (data == "true")
return true;
else
return false;
}
}
},
messages: {
userName: {
required: "请输入用户名,3-16个字符(字母、数字、下划线),注册后不能更改",
minlength: "用户名长度不能小于3个字符",
maxlength: "用户名长度不能大于16个字符",
remote: "用户名不可用"
}
}
});
参数:
<form method="get" class="cmxform" id="form1" action="">
<label>邮政编码:<input type="text" name="zip" id="zip"></label><br>
<br>
<input type="submit" value="提交">
</form>
<script src="./js/jquery-1.9.1.js"></script>
<script src="./js/jquery.validate-1.14.0.js"></script>
<script>
$(function () {
jQuery.validator.addMethod("isZipCode", function (value, element, params) {
var tel = /^[0-9]{6}$/;
console.log(params);
return this.optional(element) || (tel.test(value));
}, "请正确填写您的邮政编码");
$("#form1").validate({
debug: true,
rules: {
zip: {required: true,"isZipCode":{a:1,b:2} },
},
});
});
</script>
$("#myform").validate({
groups: {
username: "fname lname"
},
errorPlacement: function(error, element) {
if (element.attr("name") == "fname"
|| element.attr("name") == "lname" )
error.insertAfter("#lastname");
else
error.insertAfter(element);
},
debug:true
});
https://my.oschina.net/u/4382009/blog/3846121
onfocusout/onkeyup的默认值是false,如果需要开启对当前文本域的验证,则应该写成:
onfocusout: function(element) { $(element).valid(); }
onkeyup: function(element) { $(element).valid(); }
$("#myform").validate({
meta: "validate"
})
<input type="text" name="email" class="{validate:{ required: true, email:true}}" />
$("#myform").validate({
groups: {
username: "fname lname"
},
errorPlacement: function(error, element) {
if (element.attr("name") == "fname"
|| element.attr("name") == "lname" )
error.insertAfter("#lastname");
else
error.insertAfter(element);
},
debug:true
})
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title></title>
</head>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script src="http://www.softwhy.com/demo/jQuery/js/jquery.validate.js"></script>
<script src="http://www.softwhy.com/demo/jQuery/js/messages_zh.js"></script>
<script>
$(document).ready(function () {
$("#myform").validate({
errorClass: "error",
errorElement: "span",
wrapper: "li",
errorLabelContainer: $("#ant ul"),
errorContainer: $("#ant"),
rules: {
username: "required",
pw: "required",
email: {
required: true,
email: true
}
},
messages: {
name: "用户名是必填项目",
pw: "密码是必填项目",
email: {
required: "邮箱是必填项目",
email: "邮箱格式不正确"
}
}
});
});
</script>
</head>
<body>
<div id="ant">
<ul></ul>
</div>
<form id="myform">
<label for="">姓名:<input type="text" name="username" /></label>
<label for="">密码:<input type="password" name="pw" /></label>
<label for="">邮箱:<input type="text" name="email" /></label>
<input type="submit" value="提交">
<input type="reset" value="重置">
</form>
</body>
</html>
$(".selector").validate({
showErrors: function(errorMap, errorList) {
$("#summary").html("Your form contains "
+ this.numberOfInvalids()
+ " errors, see details below.");
this.defaultShowErrors();
}
})
$("#myform").validate({
errorPlacement: function(error, element) {
error.appendTo( element.parent("td").next("td") );
},
debug:true
})
$("#myform").validate({
//success: "valid",
success: function(label) {
label.addClass("valid").text("Ok!")
}
})
$(".selector").validate({
highlight: function(element, errorClass) {
$(element).addClass(errorClass);
$(element.form).find("label[for=" + element.id + "]")
.addClass(errorClass);
},
unhighlight: function(element, errorClass) {
$(element).removeClass(errorClass);
$(element.form).find("label[for=" + element.id + "]")
.removeClass(errorClass);
}
});
<form method="get" class="cmxform" id="form1" action="">
是否必填信息:
<label>是<input type="radio" name="checkInfo" value="1"></label>
<label>否<input type="radio" name="checkInfo" value="0"></label>
<br>
<label>信息输入:<input type="text" name="info" id="info"></label>
<br>
<input type="submit" value="提交" id="btn">
</form>
<script src="./js/jquery-1.9.1.js"></script>
<script src="./js/jquery.validate.js"></script>
<script>
$(function () {
$("#form1").validate({
debug: true, //只测试不提交
checkInfo: 'required'
});
//当点击“是”时,信息输入框为必填
$("#btn").click(function () {
//方式一
if ($("input[name='checkInfo']:checked").val() === '1') {
//添加三种校验规则:必填,最少添加3个字符,最多为7个字符
$("#info").rules('add', { 'required': true, 'minlength': 3, maxlength: 7 })
} else {
//如果不是必填的时候,将必填和最少字符的规则移除
$("#info").rules('remove', 'required minlength');
}
//方式二:required可以使用表达式
// $("#info").rules('add', { 'required': function (){
// return $("input[name='checkInfo']:checked").val() === '1';
// }});
});
});
</script>
<form method="get" class="cmxform" id="form1" action="">
<!-- 信息1添加属性required -->
<label>信息1:<input type="text" name="info1" id="info1" required></label><br>
<label>信息2:<input type="text" name="info2" id="info2"></label><br>
<label>信息3:<input type="text" name="info3" id="info3"></label><br>
<br>
<button id="btn">提交</button>
</form>
<script src="./js/jquery-1.9.1.js"></script>
<script src="./js/jquery.validate-1.14.0.js"></script>
<script>
$(function () {
var validator = $("#form1").validate({
debug:true,
rules:{
info2: {'required': true},
}
});
$("#info3").rules('add', 'required');
$("#btn").click(function () {
//方式一
if($("#form1").valid()){ //验证表单通过后提交
console.log('验证通过');
$("#form1").submit();
}else{
console.log('验证不通过');
}
//方式二
//if(validator.form()){ //验证表单通过后提交
//console.log('验证通过');
//$("#form1").submit();
//}else{
//console.log('验证不通过');
//}
});
});
</script>
<form id="myform">
<input value="" title='""'>
<input value=" " title='" "'>
<input value="abc" title='"abc"'>
<input type="checkbox" name="newsletter" checked="checked" value="Monthly" />
<input type="checkbox" name="newsletter" value="Yearly" />
<div></div>
</form>
<script src="./js/jquery-1.9.1.js"></script>
<script src="./js/jquery.validate-1.14.0.js"></script>
<script>
$("input:blank").css("background-color", "#bbbbff");
$("input:filled").css("background-color", "#e87777");
function countUnchecked() {
var n = $(":checkbox:unchecked").length;
$("div").text(n + (n == 1 ? " is" : " are") + " unchecked!");
}
countUnchecked();
$(":checkbox:checkbox").click(countUnchecked);
</script>
<form method="get" class="cmxform" id="form1" action="">
<label>信息:<input type="text" name="info" id="info"></label><br>
<br>
<button id="btn">提交</button>
</form>
<script src="./js/jquery-1.9.1.js"></script>
<script src="./js/jquery.validate-1.14.0.js"></script>
<script>
$(function () {
var validator = $("#form1").validate({
debug: true,
rules: {
//添加两个验证规则
info: { 'required': true, minlength: 3 },
}
});
$("#btn").click(function () {
if (validator.element('#info')) {
console.log('info验证通过');
$("#form1").submit();
} else {
console.log('info验证不通过');
}
});
});
</script>
<form method="get" class="cmxform" id="form1" action="">
<!-- 信息1添加属性required -->
<label>信息1:<input type="text" name="info1" id="info1"></label><br>
<label>信息2:<input type="text" name="info2" id="info2"></label><br>
<br>
<button id="submit">提交</button>
</form>
<!-- 注意重置的位置,放在form表单中不生效 -->
<button id="reset">重置</button>
<script src="./js/jquery-1.9.1.js"></script>
<script src="./js/jquery.validate-1.14.0.js"></script>
<script>
$(function () {
var validator = $("#form1").validate({
rules:{
info1: {'required': true},
info2: {'required': true},
}
});
$("#reset").click(function () {
validator.resetForm();
});
});
</script>
<form method="get" class="cmxform" id="form1" action="">
<!-- 信息1添加属性required -->
<label>信息1:<input type="text" name="info1" id="info1" required></label><br>
<label>信息2:<input type="text" name="info2" id="info2"></label><br>
<label>信息3:<input type="text" name="info3" id="info3"></label><br>
<div id="summary"></div>
<br>
<input type="submit" value="提交">
</form>
<script src="./js/jquery-1.9.1.js"></script>
<script src="./js/jquery.validate-1.14.0.js"></script>
<script>
$(function () {
var validator = $("#form1").validate({
debug: true,
rules: {
info1: { 'required': true, minlength: 4 },
info2: { 'required': true },
info3: { 'required': true },
},
invalidHandler: function () { //表单验证不通过时触发该方法
$("#summary").text(validator.numberOfInvalids() + " 字段是无效的");
}
});
});
</script>
<form method="get" class="cmxform" id="form1" action="">
<label>请输入信息:<input type="text" name="info" id="info" class="rules1"></label><br>
<label>请输入爱好:<input type="text" name="hobby" id="hobby" class="rules2"></label><br>
<label>请输入账号:<input type="text" name="account" id="account" class="rules3"></label><br>
<br>
<input type="submit" value="提交">
</form>
<script src="./js/jquery-1.9.1.js"></script>
<script src="./js/jquery.validate-1.14.0.js"></script>
<script>
$(function () {
//方式一
jQuery.validator.addClassRules('rules1', {
required: true,
minlength: 3,
});
//方式二
jQuery.validator.addClassRules({
'rules2': {
required: true,
minlength: 2,
},
'rules3':{
required: true,
minlength: 4,
}
});
$("#form1").validate({
debug: true,
});
});
</script>
动态添加校验规则要在初始化验证之后添加,否则就会报该错误。
正确方式如下:
$form.validate({...});
$(".course-situation-box .teachingReformConstructionAssoc").rules("add", {'required': true});