我正在使用“jQuery 验证插件 1.7”。
为什么多个“$(:input)”共享同名元素没有被验证的问题
是 $.validator.element 方法:
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() {
!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;
});
},
条件
if ( this.name in rulesCache ||.....
评估共享相同名称的第二个和下一个元素 true....
解决方案将具有以下条件:
(this.id || this.name) 在 rulesCache
对不起,JS 清教徒,(this.id || this.name) 不是 100%...
当然,
rulesCache[this.name] = true;
行也必须适当更改。
所以 $.validator.prototype.elements 方法将是:
$(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 () {
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;
});
};
}
});