jquery.validate多个相同name属性input只验证第一个的问题

原因就在 select only the first element for each name, and only those with rules specified,对于表单验证validate只做相同name的第一个input校验

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() {
            !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;
        });
    },

解决方式一:去掉单个name的验证,这样所有的相同name都可以进行验证

if ($.validator) {
  $.validator.prototype.elements = function () {
   var validator = this,
   rulesCache = {};
   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);
   }
   rulesCache[this.name] = true;
   return true;
 });
 }
}

解决方式二:添加id的,只要保证id和name有一个不同就可以进行验证

if ($.validator) {
  $.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 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;
          });
      }
    }

参考:Using JQuery Validate Plugin to validate multiple form fields with identical names

你可能感兴趣的:(jquery.validate多个相同name属性input只验证第一个的问题)