文章目录
1. 核心代码
直接引入一下代码,无需进行修改,就能够解决多个相同name 的验证无效问题。
注: id 不能相同 。 (原因见 :原理介绍)
if ($.validator) {
$.validator.prototype.elements = function () {
var validator = this,
rulesCache = {};
return $([]).add(this.currentForm.elements)
.filter(":input")
.not(":submit, :reset, :image, [disabled]")
.not(this.settings.ignore)
.filter(function () {
var elementIdentification = this.id || this.name;
!elementIdentification && validator.settings.debug && window.console && console.error("%o has no id nor name assigned", this);
if (elementIdentification in rulesCache || !validator.objectLength($(this).rules()))
return false;
rulesCache[elementIdentification] = true;
return true;
});
};
}
2. 原理
jquery 默认 验证方式是根据 name 来验证的,加入以上代码,使得 当存在多个相同 name 的时候,会 根据id
来进行 验证
3. 基础代码(jquery 验证)
$("#form1").validate({
rules: { //email:true, url:true, creditcard :true
budgetTime: {
required:true, // 必填项
digits: true, // 整数
minlength: 4,
maxlength: 4
} ,
budgetAmount: {
required:true,
number: true // 数字
}
},
messages: {
budgetTime: {
},
budgetAmount: {
}
}
});
4. jquery 验证参数 介绍
messages: {
required: "必填字段",
remote: "请修正该字段",
email: "请输入正确格式的电子邮件",
url: "请输入合法的网址",
date: "请输入合法的日期",
dateISO: "请输入合法的日期 ",
number: "请输入合法的数字",
digits: "只能输入整数",
creditcard: "请输入合法的信用卡号",
equalTo: "请再次输入相同的值",
accept: "请输入拥有合法后缀名的字符串",
maxlength: $.validator.format("字符串长度不能超过 {0}"),
minlength: $.validator.format("字符串长度不能少于{0}"),
rangelength: $.validator.format("请输入一个长度介于 {0} 和 {1} 之间的字符串"),
range: $.validator.format("请输入一个介于 {0} 和 {1} 之间的值"),
max: $.validator.format("输入值不能大于 {0}"),
min: $.validator.format("输入值不能小于{0}")
},
4. 依赖的文件
jquery.validate.js
5. jquery 源文件 验证代码
prototype: {
elements: function() {
var validator = this,
rulesCache = {};
// select all valid inputs inside the form (no submit or reset buttons)
return $(this.currentForm)
.find("input, select, textarea")
.not(":submit, :reset, :image, [disabled]")
.not( this.settings.ignore )
.filter(function() {
if ( !this.name && validator.settings.debug && window.console ) {
console.error( "%o has no name assigned", this);
}
/** select only the first element for each name, and only
those with rules specified **/
if ( this.name in rulesCache || !validator.objectLength($(this).rules()) ) {
return false;
}
rulesCache[this.name] = true;
return true;
}
);
}
}
6. 自定义验证提示
jQuery.validator.addMethod("myselfValidator", function(value, element) { // value:当前元素的值,element:当前标签
return !!value; // 不能为空
}, "返回false 时的提示信息!");
6-a 自定义验证调用
$("#form").validate({
rules:{
userName:{
required : true
},
userSex:{
myselfValidator : true // 自定义的验证
},userPassword:{
required: true,
minlength: 6
}
},messages :{
userName:{ // 验证方法默认提示
},
userSex:{
},
userPassWord:{ // 覆盖默认方法的提示信息
required:"密码不能为空",
minlength:"密码最小的长度为6"
}
}
});