下面搜集了五种方法,主要还是前两个提供了解决方案,第三种需要修改jQuery源码:
修复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属性来验证
-------------------------------------------------------------------------------------------
用下面这种方式应该能解决:(http://stackoverflow.com/questions/2589670/using-jquery-validate-with-multiple-fields-of-the-same-name)
$(function(){ $("#myform").validate(); $("[name=field]").each(function(){ $(this).rules("add", { required: true, email: true, messages: { required: "Specify a valid email" } }); });});
----------------------------------------------------------------------------------
jquery.validate.js 相同name的多个元素只能验证第一个元素的解决办法
动态生成的相同name的元素验证只会取第一个.
很恼火的问题.只有将jquery.validate.js中的对相同name的元素判断注释掉.
但是不知道会不会引起其他地方的BUG
希望以后jquery.validate.js能做针对元素ID进行验证而不仅仅针对元素name验证.
方法:
将484行的代码注释掉即可
// 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; }
新闻热点
疑难解答
图片精选