【问题标题】:Using jquery validate with multiple fields of the same name使用 jquery 验证多个同名字段
【发布时间】:2010-04-07 02:39:30
【问题描述】:

我正在尝试让 jquery validate 在多个字段上工作。原因是我添加了动态生成的字段,它们只是一个电话号码列表,从无到所需数量。一个按钮添加另一个数字。

所以我想我会整理一个基本示例,并遵循以下链接中接受的答案中的概念:

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

但是,它没有做任何有用的事情。为什么它不起作用?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/lib/jquery.delegate.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>


<script>
  $("#submit").click(function(){
    $("field").each(function(){
      $(this).rules("add", {
        required: true,
        email: true,
        messages: {
          required: "Specify a valid email"
        }
      });   
    })
  });


  $(document).ready(function(){
    $("#myform").validate();
  });
</script>

</head>
<body>

<form id="myform">
  <label for="field">Required, email: </label>
  <input class="left" id="field" name="field" />
  <input class="left" id="field" name="field" />
  <input class="left" id="field" name="field" />
  <input class="left" id="field" name="field" />
  <br/>
  <input type="submit" value="Validate!" id="submit" name="submit" />
</form>

</body>
</html>

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    这个:$("field").each(function(){
    应该是:$("[name=field]").each(function(){

    此外,您的 ID 应该是唯一的,如果不是这样,您将获得不可预知的行为。此外,您应该移动添加到 document.ready 中的规则,如下所示(现在这是您的全部脚本):

    $(function(){
      $("#myform").validate();
      $("[name=field]").each(function(){
         $(this).rules("add", {
           required: true,
           email: true,
           messages: {
             required: "Specify a valid email"
           }
         });   
       });
    });
    

    【讨论】:

    • 您的解决方案对我来说只是以这种方式选择输入:$("[name^=foo][name$=bar]").each(function()。那将选择输入其名称属性以“foo”开头并以“bar”结尾,例如“foo_bar”,但它不适用于“foobar”...:)
    • @user248959 - 它应该也适用于name="foobar"(因为它符合标准),你可以在这里测试它:jsfiddle.net/nick_craver/fM52H
    • @NickCraver ,但它只验证我的第一个文本框
    • @PratikJoshi 您是否有单独表单的文本框,都具有相同的 ID?那会有这种行为,但不是有效的 HTML - ID 应该是唯一的。
    • 对于这个结构我试过了,但没用 =>
    【解决方案2】:

    @pratik JqueryValidation维护rulesCache,需要修改核心库。

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

    只需评论 rulesCache[this.name] = true;

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

    如果您不想更改核心库文件。还有另一种解决方案。只需覆盖现有的核心功能。

    $.validator.prototype.checkForm = function (){
      this.prepareForm();
        for ( var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++ ) {
            if (this.findByName( elements[i].name ).length != undefined && this.findByName( elements[i].name ).length > 1) {
                for (var cnt = 0; cnt < this.findByName( elements[i].name ).length; cnt++) {
                    this.check( this.findByName( elements[i].name )[cnt] );
                }
            } 
            else {
                this.check( elements[i] );
            }
        }
        return this.valid();
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-08
      • 2014-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多