在使用Jquery validate中遇到一个问题,当表单元素有name相同字段时,validate只校验表单元素name第一个值是否通过校验,比如
<input type="text" name="userName"/>
<input type="text" name="userName"/>
<input type="text" name="userName"/>
<select name="favour"></select>
<select name="favour"></select>
<select name="favour"></select>
这时候,jquery validate,只会校验第一个元素,看了一下源码(https://cdn.bootcss.com/jquery-validate/1.17.0/jquery.validate.js),是因为它在获取form元素时,做了一层cache处理。
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, [contenteditable]" )
.not( ":submit, :reset, :image, :disabled" )
.not( this.settings.ignore )
.filter( function() {
var name = this.name || $( this ).attr( "name" ); // For contenteditable
if ( !name && validator.settings.debug && window.console ) {
console.error( "%o has no name assigned", this );
}
// Set form expando on contenteditable
if ( this.hasAttribute( "contenteditable" ) ) {
this.form = $( this ).closest( "form" )[ 0 ];
this.name = name;
}
// Select only the first element for each name, and only those with rules specified,缓存判断
if ( name in rulesCache || !validator.objectLength( $( this ).rules() ) ) {
return false;
}
// 在这里做了一层Cache,如果下次再来相同的Name,则不会再进入validate的校验List
rulesCache[ name ] = true;
return true;
} );
},
解决办法
1. 我们可以更改源码cache的key的名字或者在Jquery页面load完毕后,修改property上的validate原型方法,它使用name可能会造成这种bug,那我们使用Id,一般Id是不会重复的,如果Id不存在,我们再使用name来做为cache的key,简单来说,就是一行代码
var name = this.id || this.name || $( this ).attr( "name" ); // For contenteditable
比原有的
var name = this.name || $( this ).attr( "name" ); // For contenteditable
多了一个 this.id 判断。
2. 页面加载完成后修改的方式:
$(function() {
if ($.validator) {
//fix: when several input elements shares the same name, but has different id-ies....
$.validator.prototype.elements = function() {
var validator = this,
rulesCache = {};
// select all valid inputs inside the form (no submit or reset buttons)
// workaround $Query([]).add until http://dev.jquery.com/ticket/2114 is solved
return $([]).add(this.currentForm.elements).filter(":input").not(":submit, :reset, :image, [disabled]").not(this.settings.ignore).filter(function() {
// 这里加入ID判断
var elementIdentification = this.id || this.name; ! elementIdentification && validator.settings.debug && window.console && console.error("%o has no id nor name assigned", this);
// select only the first element for each name, and only those with rules specified
if (elementIdentification in rulesCache || !validator.objectLength($(this).rules())) return false;
rulesCache[elementIdentification] = true;
return true;
});
};
}
});
记得给你name相同的表单元素添加id哦~