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

来源:互联网 发布:mac如何进行文件管理 编辑:程序博客网 时间:2024/06/05 10:08

在项目开发中,通常会遇到一个表格构成的表单,那么表单里面就可能会有几个元素的名字相同,针对这种情况在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;            });        },
针对上面的代码可以看出,仅仅需要注释掉标注处的if语句即可。



阅读全文
0 0
原创粉丝点击