【问题标题】:Validate Dynamically Added Input fields验证动态添加的输入字段
【发布时间】:2012-07-17 04:29:50
【问题描述】:

我已经为以下表单使用了this jquery 验证插件。

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>

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

    function addInput() {
        var obj = document.getElementById("list").cloneNode(true);
        document.getElementById('parent').appendChild(obj);
    }
</script>

<form id="commentForm" method="get" action="">
    <p id="parent">
        <input id="list"  class="required" />
    </p>

    <input class="submit" type="submit" value="Submit"/>
    <input type="button" value="add" onClick="addInput()" />
</form>

单击添加按钮时,会动态添加新输入。但是,当提交表单时,仅验证第一个输入字段。如何验证动态添加的输入? 谢谢...

【问题讨论】:

标签: javascript jquery html jquery-validate


【解决方案1】:

您的输入应该具有“名称”属性。您需要动态添加规则,一种选择是在表单提交时添加它们。

这是我测试过并且有效的解决方案:

<script type="text/javascript">
   $(document).ready(function() {
        var numberIncr = 1; // used to increment the name for the inputs

        function addInput() {
            $('#inputs').append($('<input class="comment" name="name'+numberIncr+'" />'));
            numberIncr++;
        }

        $('form.commentForm').on('submit', function(event) {

            // adding rules for inputs with class 'comment'
            $('input.comment').each(function() {
                $(this).rules("add", 
                    {
                        required: true
                    })
            });            

            // prevent default submit action         
            event.preventDefault();

            // test if form is valid 
            if($('form.commentForm').validate().form()) {
                console.log("validates");
            } else {
                console.log("does not validate");
            }
        })

        // set handler for addInput button click
        $("#addInput").on('click', addInput);

        // initialize the validator
        $('form.commentForm').validate();

   });


</script>

还有html表单部分:

<form class="commentForm" method="get" action="">
    <div>

        <p id="inputs">    
            <input class="comment" name="name0" />
        </p>

    <input class="submit" type="submit" value="Submit" />
    <input type="button" value="add" id="addInput" />

    </div>
</form>

祝你好运!如果适合您,请批准答案!

【讨论】:

  • 非常感谢@Angel 的努力。它像魔术一样工作。很棒的工作:)
  • FWIW,您可以在 document.ready 上调用一次 validate,然后在 addInput 函数中添加您的规则。如果您想显示验证成功/失败,请将处理程序附加到 submitHandlerinvalidHandler
  • 是的,这可能有效,您需要为最后添加的输入添加规则,例如 $('input.comment:last').rules('add', {});但我发现将所有验证部分放在同一个地方更直接。
  • +1 表示动态字段的答案。我使用 addInput 预先完成,以获得即时模糊验证,而不是等待提交。
  • 巨大的陷阱让我发疯了...动态字段必须具有name 属性,否则验证将不起作用。谢谢@Angel,您的回答。
【解决方案2】:

添加新字段后重置表单验证。

function resetFormValidator(formId) {
    $(formId).removeData('validator');
    $(formId).removeData('unobtrusiveValidation');
    $.validator.unobtrusive.parse(formId);
}

【讨论】:

  • 这个解决方案好多了
  • 这个函数需要从哪里调用?在提交表单时,或者添加新字段的javascript方法?
  • 当我使用这个时,我收到了这个错误:Uncaught TypeError: Cannot read property 'parse' of undefined
  • 添加新字段后,通常会在添加新字段函数中调用此函数。这样它就会找到新的领域。不确定错误。某处丢失了一些东西......
【解决方案3】:

您需要在添加动态内容后重新解析表单以验证内容

$('form').data('validator', null);
$.validator.unobtrusive.parse($('form'));

【讨论】:

    【解决方案4】:

    由于缺少属性名称,发布的一个 mahesh 无法正常工作:

    所以不是

    <input id="list" class="required"  />
    

    你可以使用:

    <input id="list" name="list" class="required"  />
    

    Modified version

    【讨论】:

      【解决方案5】:

      jquery 验证插件版本工作正常 v1.15.0v1.17.0 不适合我。

      $(document).find('#add_patient_form').validate({
                ignore: [],
                rules:{
                  'email[]':
                  {
                    required:true,
                  },               
                },
                messages:{
                  'email[]':
                  {
                    'required':'Required'
                  },            
                },    
              });
      

      【讨论】:

        【解决方案6】:

        关于@RitchieD 响应,这里有一个 jQuery 插件版本,如果您使用 jQuery,可以让事情变得更容易。

        (function ($) {
        
            $.fn.initValidation = function () {
        
                $(this).removeData("validator");
                $(this).removeData("unobtrusiveValidation");
                $.validator.unobtrusive.parse(this);
        
                return this;
            };
        
        }(jQuery));
        

        可以这样使用:

        $("#SomeForm").initValidation();
        

        【讨论】:

          【解决方案7】:
          $('#form-btn').click(function () {
          //set global rules & messages array to use in validator
             var rules = {};
             var messages = {};
          //get input, select, textarea of form
             $('#formId').find('input, select, textarea').each(function () {
                var name = $(this).attr('name');
                rules[name] = {};
                messages[name] = {};
          
                rules[name] = {required: true}; // set required true against every name
          //apply more rules, you can also apply custom rules & messages
                if (name === "email") {
                   rules[name].email = true;
                   //messages[name].email = "Please provide valid email";
                }
                else if(name==='url'){
                  rules[name].required = false; // url filed is not required
          //add other rules & messages
                }
             });
          //submit form and use above created global rules & messages array
             $('#formId').submit(function (e) {
                      e.preventDefault();
                  }).validate({
                      rules: rules,
                      messages: messages,
                      submitHandler: function (form) {
                      console.log("validation success");
                      }
                  });
          });
          

          【讨论】:

          • 这对我有用。我喜欢这种方法,因为他没有重新初始化表单验证器,而是等待用户尝试提交,然后在 each() 中添加规则并使用所有动态生成的规则初始化表单验证器。
          【解决方案8】:

          尝试使用输入数组:

          <form action="try.php" method="post">
              <div id="events_wrapper">
                  <div id="sub_events">
                      <input type="text" name="firstname[]" />                                       
                  </div>
              </div>
              <input type="button" id="add_another_event" name="add_another_event" value="Add Another" />
              <input type="submit" name="submit" value="submit" />
          </form>
          

          并添加此脚本和jQuery,使用 foreach() 来检索 $_POST'ed 的数据:

          <script>                                                                                    
              $(document).ready(function(){
                  $("#add_another_event").click(function(){
                  var $address = $('#sub_events');
                  var num = $('.clonedAddress').length; // there are 5 children inside each address so the prevCloned address * 5 + original
                  var newNum = num + 1;
                  var newElem = $address.clone().attr('id', 'address' + newNum).addClass('clonedAddress');
          
                  //set all div id's and the input id's
                  newElem.children('div').each (function (i) {
                      this.id = 'input' + (newNum*5 + i);
                  });
          
                  newElem.find('input').each (function () {
                      this.id = this.id + newNum;
                      this.name = this.name + newNum;
                  });
          
                  if (num > 0) {
                      $('.clonedAddress:last').after(newElem);
                  } else {
                      $address.after(newElem);
                  }
          
                  $('#btnDel').removeAttr('disabled');
                  });
          
                  $("#remove").click(function(){
          
                  });
          
              });
          </script>
          

          【讨论】:

            【解决方案9】:

            如果你有一个表单,你可以像这样添加一个类名:

            <form id="my-form">
              <input class="js-input" type="text" name="samplename" />
              <input class="js-input" type="text" name="samplename" />
              <input class="submit" type="submit" value="Submit" />
            </form>
            

            然后您可以使用验证器的addClassRules 方法来添加您的规则,这将适用于所有动态添加的输入:

            $(document).ready(function() {
              $.validator.addClassRules('js-input', {
                required: true,
              });
              //validate the form
              $('#my-form').validate();
            });
            

            【讨论】:

              【解决方案10】:
              <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
              <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/jquery-validation@1.17.0/dist/jquery.validate.js"></script>
              
              <script>
                  $(document).ready(function(){
                      $("#commentForm").validate();
                  });
              
                  function addInput() {
              
                      var indexVal = $("#index").val();
                      var index = parseInt(indexVal) + 1
                      var obj = '<input id="list'+index+'" name=list['+index+']  class="required" />'
                      $("#parent").append(obj);
              
                      $("#list"+index).rules("add", "required");
                      $("#index").val(index)
                  }
              </script>
              
              <form id="commentForm" method="get" action="">
                  <input type="hidden" name="index" name="list[1]" id="index" value="1">
                  <p id="parent">
                      <input id="list1"  class="required" />
                  </p>
                  <input class="submit" type="submit" value="Submit"/>
                  <input type="button" value="add" onClick="addInput()" />
              </form>
              

              【讨论】:

              • 你能多解释一下你的解决方案,让它不仅仅是代码吗?
              猜你喜欢
              • 2021-05-21
              • 2015-12-27
              • 2014-12-19
              • 2013-06-27
              • 2015-05-16
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多