Jquery validate验证表单时多个name相同的元素只验证第一个的问题

本文解决jQuery Validate插件在处理相同name属性元素时的验证问题。通过修改插件源码,确保每个元素都能被正确验证,特别是动态生成的表单。引入代码段并为元素添加id属性,实现更精确的验证。

修复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://xinklabi.iteye.com/blog/2128781

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值