jQuery Validate--针对多个相同名称的元素的验证

在项目开发中,通常会遇到一个表格构成的表单,那么表单里面就可能会有几个元素的名字相同,针对这种情况在validate默认的条件下是只能验证第一个,而后面的元素就不能得到验证,那么要解决这种问题就有以下两种处理方式。

注意:无论采用下面哪种处理方式,相同名称的元素都必须拥有id,否则是没有任何效果的。

方法一:

在需要验证的页面的js文件中添加以下代码即可:

 

/**
 * 针对具有相同名称的元素的验证的处理
 */
$(function(){
    if ($.validator) {
        $.validator.prototype.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")
                .not(":submit, :reset, :image, [disabled]")
                .not(this.settings.ignore)
                .filter(function () {
                    if (!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;
                });
        }
    }
});

方法二:修改jQuery.validate.js源码

 

 

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")
            .not(":submit, :reset, :image, [disabled]")
            .not( this.settings.ignore )
            .filter(function() {
                if ( !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;
            });
        },	return false;
                //     }

                rulesCache[this.name] = true;
                return true;
            });
        },

针对上面的代码可以看出,仅仅需要注释掉标注处的if语句即可。

 


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值