修复jquery.validate插件中name属性相同(如name=’a[]‘)时验证的bug
使用jquery.validate插件http://jqueryvalidation.org/,当节点的name相同时候,脚本特意忽略剩余节点,导致所有相关节点的errMsg都显示在第一个相关节点上。这个bug在动态生成表单时候影响比较大。
通过查询资料,找到一个解决方案:
http://stackoverflow.com/questions/931687/using-jquery-validate-plugin-to-validate-multiple-form-fields-with-identical-nam
具体内容为
$(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;
});
};
}
})
在页面上引入以上代码,然后给相关节点加上id属性,当name属性相同时候会以id属性来验证
本文解决jQuery Validate插件在处理相同name属性元素时的验证问题。通过修改插件源码,确保每个元素都能被正确验证,特别是动态生成的表单。引入代码段并为元素添加id属性,实现更精确的验证。
3万+

被折叠的 条评论
为什么被折叠?



