jQuery Validate--针对多个相同名称的元素的验证
首页 > >    作者:lininn   2018年10月16日 16:48 星期二   热度:2062°   百度已收录  
时间:2018-10-16 16:48   热度:2062° 
在项目开发中,通常会遇到一个表格构成的表单,那么表单里面就可能会有几个元素的名字相同,针对这种情况在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语句即可。

二维码加载中...
本文作者:lininn      文章标题: jQuery Validate--针对多个相同名称的元素的验证
本文地址:?post=247
版权声明:若无注明,本文皆为“覆手为雨”原创,转载请保留文章出处。
分享本文至:

返回顶部    首页    手机版本    后花园   会员注册   
版权所有:覆手为雨    站长: lininn