简体   繁体   English

jQuery验证忽略动态添加的字段

[英]jquery validate ignores dynamically added fields

Jquery validate validates the form fields that are already in the DOM as well as fields that are added dynamically. Jquery validate验证DOM中已经存在的表单字段以及动态添加的字段。 But if the fields that are NOT dynamically added pass validation, the form submits ignoring the dynamically added fields. 但是,如果未动态添加的字段通过验证,则表单将忽略动态添加的字段提交。

Here is a snapshot: 这是快照: 快照

Here is my code: 这是我的代码:

 $('#milestone-form').validate({ // initialize the plugin
        rules: {
            "milestone[]": {
                required: true,
                minlength: 3,
            },
            "deadline[]": {
                required: true,
                minlength: 3,
            },
            "amount[]": {
                required: true,
                minlength: 2,
            },

        },
        submitHandler: function(form) {
              var data = $("#milestone-form").serialize();
                $.ajax({
                    type:"POST",
                    url:"ajax/scripts/crt_ms.php",
                    data:data,
                    success:function(data){ 
                        if(!data){alert("Something went wrong")}else{alert("Success")}
                        $(document).off();
                        },  
                    });
            },
    });
    //Validation End

  $(document).on('click', ".add", function(){
  $(flieds).insertAfter($(this).closest("#fields"));
  $('.field').each(function() {
  $(this).rules('add', {
    required: true,
        });
    });
}); 

$(".save-ms").click(function(){
    if($('#milestone-form').valid()){
        //$("#milestone-form").submit();
        alert("POSTED");
         return false;
    } else { alert("ERROR");}
});

All my <input> elements have a class=".field" attribute. 我所有的<input>元素都有一个class=".field"属性。

Also, I noticed one thing that all the dynamic fields do not get a error LABEL instead only have a class to define it as invalid. 另外,我注意到一件事,所有动态字段都不会得到错误LABEL,而是只有一个类将其定义为无效。

I have been trying the whole day to do this but just not happening. 我整天都在尝试这样做,但没有发生。

It is simple. 很简单。 Jquery validate doesn't validate multiple elements with the same name. jQuery validate不会验证具有相同名称的多个元素。

So the solution I found is here , originally from here 所以我找到的解决方案是在这里 ,最初是从这里

I just had to add this. 我只需要添加它。

$(document).ready(function(){
$.validator.prototype.checkForm = function () {
            //overriden in a specific page
  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();
},
};

In your own answer you used a lot of repeated searches through the DOM elements. 在您自己的答案中,您对DOM元素进行了很多重复的搜索。 Per loop iteration you did at least four dom searches, sometimes even just for the simple length variable. 对于每个循环迭代,您至少进行了四个dom搜索,有时甚至只是针对简单的length变量。

This puts an unecessary load on the browser. 这给浏览器带来了不必要的负担。 Also I'd suggest making use of the native jQuery functions to help you iterate these loops and then use some scopeing to help you store relevenant references, like one to the validator. 另外,我建议使用本机jQuery函数来帮助您迭代这些循环,然后使用一些作用域来帮助您存储相关引用,例如对验证者的引用。

Suggested reading: 建议阅读:

What is the scope of variables in JavaScript? JavaScript中变量的范围是什么?
Performance of jQuery selectors vs local variables jQuery选择器的性能与局部变量

$.validator.prototype.checkForm = function () {
        //overriden in a specific page
        this.prepareForm();
        // Scoped variable.  
        var that = this;
        $(this.elements).each(function(index,elem) {
            // Search only once. big speed improv
            var seek = that.findByName(elem.name);
            // undefined and 0 is false by default
            if (seek.length && seek.length > 1) {
                seek.each(function(index,duplicate) {
                    // Notice the use the reference that from the outerscope. 
                    // `that` int his case refers to the the validator object.
                    that.check(duplicate);
                });
            }
          else {
              that.check(seek);
          }
       });
    };

 $(document).ready(function(){ $('#milestone-form').validate({ // initialize the plugin rules: { "milestone[]": { required: true, minlength: 3, }, "deadline[]": { required: true, minlength: 3, }, "amount[]": { required: true, minlength: 2, }, }, submitHandler: function(form) { var data = $("#milestone-form").serialize(); $.ajax({ type:"POST", url:"#", data:data, success:function(data){ if(!data){alert("Something went wrong")}; $(document).off(); }, }); }, }); // =========================================================================== $.validator.prototype.checkForm = function () { //overriden in a specific page this.prepareForm(); // Scoped variable. var that = this; $(this.elements).each(function(index,elem) { // Search only once. big speed improv var seek = that.findByName(elem.name); // undefined and 0 is false by default if (seek.length && seek.length > 1) { seek.each(function(index,duplicate) { // Notice the use the reference that from the outerscope. // `that` int his case refers to the the validator object. that.check(duplicate); }); } else { that.check(seek); } }); }; // =========================================================================== var form= "<div id='fields'> <input type='text' name='milestone[]' placeholder='Milestone'> <input type='text' name='deadline[]' placeholder='Deadline'> <input type='text' name='amount[]' placeholder='Amount'> <input type='text' name='p[]' value='1' style='display:none;'> <span class='add halflings-icon plus'>+</span> <span class='remove halflings-icon minus'>-</span> </div>" $(document).on('click', ".add", function(){ $(form).insertAfter($(this).closest("#fields")); }); $(document).on('click', ".remove", function(){ $(this).closest('div').remove(); }); $(".save-ms").click(function(evt){ evt.preventDefault(); if($('#milestone-form').valid()){ alert("POSTED"); return false; } else { alert("All Fields are required");} }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.js"></script> <form method="post" id="milestone-form"> <div id="fields" style="width:100%;"> <input type="text" name="milestone[]" placeholder="Milestone"> <input type="text" name="deadline[]" placeholder="Deadline"> <input type="text" name="amount[]" placeholder="Amount"> <input type="text" name="p[]" value="1" style="display:none;"> <span class="add halflings-icon plus">+</span> </div> <input type="submit" name="save-ms" class="btn btn-primary save-ms" value="Create"> </form> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM