【问题标题】:jquery validate ignores dynamically added fieldsjquery validate 忽略动态添加的字段
【发布时间】:2016-02-16 19:35:36
【问题描述】:

Jquery validate 验证 DOM 中已经存在的表单字段以及动态添加的字段。但是如果不是动态添加的字段通过验证,表单提交忽略动态添加的字段。

这是一个快照:

这是我的代码:

 $('#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");}
});

我所有的<input> 元素都有一个class=".field" 属性。

另外,我注意到一件事,所有动态字段都没有得到错误 LABEL,而是只有一个类将其定义为无效。

我一整天都在尝试这样做,但没有发生。

【问题讨论】:

    标签: javascript jquery validation


    【解决方案1】:

    这很简单。 Jquery validate 不会验证具有相同名称的多个元素。

    所以我找到的解决方案是here,最初来自here

    我只需要添加这个。

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

    【讨论】:

    • 好的...答案有效,但我更喜欢这样做,它更干净,请学会存储搜索结果,而不是在几个循环中一遍又一遍地重复.您会在每次迭代中多次搜索 DOM 元素...看看kopy.io/J9q3e。通过存储变量并通过 jquery 方法对其进行迭代,您的验证将减少资源密集型且速度更快。
    • 呃,我总是在 jquery 中犯一个错误,忘记了函数的第一个参数是索引。我更正的kopy.io/TOknh
    • 好逻辑。但他们似乎是一个语法错误控制台这么说。不过好像没找到
    • 如果你可以用你的表单代码提供一个 jsfiddle 我可以修复它:-) 我只是懒得输入一个表单并设置验证器等。我只是输入了我将如何使用 jQuery each 方法来保持函数清洁。我真的建议您了解变量范围。我想带来的主要教训是:不要重复搜索。搜索一次,存储它,然后在存储的变量上做你的事情。
    • 我让它工作了 :-) jsfiddle.net/mdibbets/f4rm0ut6/14 有一些错误,但是你有很好的代码 :-)
    【解决方案2】:

    在您自己的答案中,您对 DOM 元素进行了大量重复搜索。 您在每次循环迭代中至少进行了四次 dom 搜索,有时甚至只是为了简单的长度变量。

    这会给浏览器带来不必要的负担。此外,我建议使用原生 jQuery 函数来帮助您迭代这些循环,然后使用一些作用域来帮助您存储相关引用,例如对验证器的引用。

    推荐阅读:

    What is the scope of variables in JavaScript?
    Performance of jQuery selectors vs local variables

    $.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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-02
      • 1970-01-01
      相关资源
      最近更新 更多