jQuery validator 是一款基于jQuery的表单验证插件, 非常方便实用。
例:
使用前引入需要的js:
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"> </script>
//OR
<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>
这里直接讲自定义提示信息的表单校验(默认提示文字的,直接在标签内添加校验规则即可,不需要在script中配置rules和messages。
场景: 例子中的表单id为dataForm, 并且每个表单里面的元素都绑定了name值
下面我们以id为dataForm 这个表单为例添加表单校验。
一.基本表单校验(内置验证方式)
给需要添加表单的标签添加validate()方法, rules里面的对象是name和校验规则,messages里面的对象是name和校验时候的提示信息。
所有内置验证方式详见: jqueryvalidator内置校验器
$('#dataForm').validate({
rules: {
cno: {
required: true,
maxlength: 5
},
cname: {
required:true,
maxlength: 10
},
tno:{
required:true,
maxlength: 1
}
},
messages: {
cno: {
required: "课程号不能为空",
maxlength: "课程号最多五位"
},
cname:{
required: "课程名不能为空",
maxlength: "课程名最多十位"
},
tno:{
required:"请选择老师",
maxlength: "请选择老师"
}
},
});
二.自定义校验器:
有时jquery validator内置的校验器可能无法满足我们的需求,这时候就可以自定义一个校验器,然后像调用普通校验器一样,将校验规则写在rules中,将校验提示信息写在messages中去。自定义表单校验的格式如下面例子:
//自定义: 表单校验
jQuery.validator.addMethod("isCno", function(value, element) {
var reg = /^[0-9]-[0-9][0-9][0-9]$/;
return this.optional(element) || (reg.test(value));
}, "请输入正确的课程号");
//添加到表单校验器中去: isCno:true
$('#dataForm').validate({
rules: {
cno: {
required: true,
maxlength: 5,
isCno:true
},
cname: {
required:true,
maxlength: 10
},
tno:{
required:true,
maxlength: 1
}
},
messages: {
cno: {
required: "课程号不能为空",
maxlength: "课程号最多五位",
isCno:"请输入正确的课程号格式(x-xxx)"
},
cname:{
required: "课程名不能为空",
maxlength: "课程名最多十位"
},
tno:{
required:"请选择老师",
maxlength: "请选择老师"
}
},
});
三.ajax请求的表单校验规则:
请求远程校验。url 通常是一个远程调用方法
例如我们希望用户在新建课程编号和课程名称的时候判断是否已经存在,已经存在时,无法提交表单。
基本格式:
// 表单校验
$('#dataForm').validate({
rules: {
cno: {
required: true,
maxlength: 5,
isCno:true,
remote: {
url: "${pageContext.request.contextPath}/course/checkCno",
data: {
cno: function () {
if(checkCno!==""&&checkCno==$("#cno").val()){
return "aAbaBcC";
}else{
return $("#cno").val();
}
}
},
dataFilter: function (data) {
if (data == "true") {
return true;
}
else {
return false;
}
}
}
},
cname: {
required:true,
maxlength: 10,
remote: {
url: "${pageContext.request.contextPath}/course/checkCname",
data: {
cname: function () {
if(checkCname!==""&&checkCname==$("#cname").val()){
return "aAbaBcC";
}else{
return $("#cname").val();
}
}
},
dataFilter: function (data) {
if (data == "true") {
return true;
}
else {
return false;
}
}
}
},
tno:{
required:true,
maxlength: 1
}
},
messages: {
cno: {
required: "课程号不能为空",
maxlength: "课程号最多五位",
isCno:"请输入正确的课程号格式(x-xxx)",
remote: "该课程号已存在!!!"
},
cname:{
required: "课程名不能为空",
maxlength: "课程名最多十位",
remote: "该课程名已存在!!!"
},
tno:{
required:"请选择老师",
maxlength: "请选择老师"
}
},
});
注意: ajax远程请求服务器校验,返回结果最终以true和false判定是否校验通过。
jquery validator 校验提示消息 默认是黑色字体, 出现在input的下方, 如果想给提示信息修改样式, 可以给label.errors设置即可