Validate dynamically generated form with jQuery Validator

寵の児 提交于 2019-12-25 02:01:21

问题


Sorry for keep asking this, but I just can't figure it out. I've reduced the question to just the bare minimum.

How can I validate a dynamically generated form? Below is my attempt, but as seen, it shows up as passing validation.

https://jsfiddle.net/j2pgobze/1/

<form id="myForm">
    <input type="text" name="email" id="email" value="bademail" >
</form>
<button id="validate">validate</button>

var myValidateObj = {
     rules: {
         email: {
             email: true
         }
     }
 };

 $(function () {

     jQuery.validator.setDefaults({
         debug: true,
         success: "valid"
     });

     $('#validate').click(function () {

         //Validate the traditional form
         var validate1 = $('#myForm').validate(myValidateObj);
         console.log('Option 1', $('#myForm'), $('#email'), $('#email').val(), validate1.element('#email'), $('#email').valid(), $('#myForm').valid());

         //Validate dynamically created form
         var input = $('<input />', {
             type: 'text',
             name: 'email',
             value: 'bademail'
         });
         //input.prop('value', 'bademail');
         var form = $('<form />').append(input);
         var validate = form.validate(myValidateObj);
         console.log('Option 2', form, input, $('#email').val(), validate.element(input), input.valid(), form.valid());
     });

 });

回答1:


  1. The button needs to be inside the form and be a type="submit" in order for the plugin to capture the click.

  2. Do not put .validate() within a click handler (See item 1). It's only used to initialize the plugin on a form. Exception, below we are creating the new form within a click handler and then immediately calling .validate() on the new form.

With these two small changes, the validation on the static form is working: jsfiddle.net/j2pgobze/3/

  1. I rewrote your DOM manipulation code for clarity. I simply duplicated the HTML for the form and gave it a new ID: http://jsfiddle.net/zem84tfp/

$(function () {

     // INITIALIZE plugin on the traditional form
     var validate1 = $('#myForm').validate(myValidateObj);

     $('#newform').one('click', function () {

         // code here to create new form; give it new ID
         // do not duplicate ID on anything else

         // INITIALIZE plugin on the new form
         var validate = $('#myForm2').validate(myValidateObj);
     });

});


来源:https://stackoverflow.com/questions/29569394/validate-dynamically-generated-form-with-jquery-validator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!