Jquery - Validating only one form out of multiple forms

戏子无情 提交于 2020-01-05 06:17:41

问题


So, I've browsed many threads on SO, but couldnt find my related query. Well, I've a webapp similar to SO, where questions are asked, and people have the liberty to comment/answer on the question (also comments on answers are allowed).

I get the Answers of a particular question via the API and form the respective HTML and append it to a div. My HTML is somewhat like this:-

<div>
   <p> Some Answer </p>
   <div class="comments"></div>
       <form id="form_62" class="comment_form" method="POST" action="URL"> <!--This id is variable-->
           <textarea rows="3" name="comment"></textarea>
           <button type="submit">Comment </button>
       </form>
    </div>
</div>

So, I append HTML like this in some div DYNAMICALLY. As you can see, there can be many answers, and hence multiple comments form.

I wrote a validator against it, which is as follow:-

$(function(){
    $(document).on('submit', '.comment_form', function(e){
        alert(111)
        form_id = $(this).id
        e.preventDefault();    
        if($(this).valid()){
            $.ajax({
                ...
            });
        }
    })

    $(this).validate({
        ignore: '',
        onsubmit : false,
        rules: {
            comment: {
                required: true,
                minlength: 10
            }
        }
    });
})

This does not works as expected.

So, my question is how can I validate my current form which is submitted?


回答1:


If any div with form is dynamically added then create one function that apply validate on form based on Id and call function when div or form added dynamically.

    function applyValidate(id){
       $(id).validate({
         ignore: '',
         onsubmit : false,
         rules: {
           comment: {
             required: true,
             minlength: 10
           }
         }
      });
   } 

If all forms are loaded in page at a time and You want to bind validate on each form then you can use below code.

$(function(){
  $(document).on('submit', '.comment_form', function(e){
    form_id = $(this).id
    e.preventDefault();    
    if($(this).valid()){
      console.log('success')
    }
  });
	
  /* If all forms are not dynamically added and rendered at once in page then you have to apply validate on each form otherwise add applyValidate(id) function outside of $(function(){}); and call applyValidate(id) function when form is dynamically added*/
  
  $('.comment_form').each(function() {  
    // attach to all form elements on page
    $(this).validate({
      ignore: '',
      onsubmit : false,
      rules: {
        comment: {
          required: true,
          minlength: 10
        }
      }
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.1/jquery.validate.js"></script>


<div>
  <p> Some Answer </p>
  <div class="comments"></div>
  <form id="form_62" class="comment_form" method="POST" action="URL"> <!--This id is variable-->
    <textarea rows="3" name="comment"></textarea>
	<button type="submit">Comment </button>
  </form>
</div>

<div>
  <p> Some Answer </p>
  <div class="comments"></div>
  <form id="form_63" class="comment_form" method="POST" action="URL"> <!--This id is variable-->
    <textarea rows="3" name="comment"></textarea>
	<button type="submit">Comment </button>
  </form>
</div>

<div>
  <p> Some Answer </p>
  <div class="comments"></div>
  <form id="form_64" class="comment_form" method="POST" action="URL"> <!--This id is variable-->
    <textarea rows="3" name="comment"></textarea>
	<button type="submit">Comment </button>
  </form>
</div>



回答2:


Problems with your code called out in my comments:

$(function(){

    // can NOT use submit handler since the validate plugin is already capturing this event
    $(document).on('submit', '.comment_form', function(e){ 

        ....
        // can NOT use 'valid()' before 'validate()' has initialized
        if($(this).valid()){ 
            ....
        }
    })

    // $(this) is meaningless here since it's not inside a pending jQuery method being invoked
    $(this).validate({
        ....
    });
})

You would not call .validate() when you submit the form. The .validate() method is only used to initialize the plugin on your form, not call validation of the form. So normally .validate() is called when the page is loaded.

Since you have forms that do not yet exist when the page is loaded, you would only call .validate() as soon as the dynamic form is created, not submitted. In other words, invoke the .validate() method as the very last step within whatever function creates this form, and since your submit button is a type="submit" the validate plugin will capture it automatically and you will not need a submit or click handler to get validation.

$(function(){

    function create_dynamic_form() {

        // code to dynamically create this form HERE


        // initialize validation on this new form ->

        $('#this-new-form-id').validate({
            ....
        });

    });

});

My example could be more efficient if you had shown us the actual code that dynamically creates the new form.



来源:https://stackoverflow.com/questions/40092806/jquery-validating-only-one-form-out-of-multiple-forms

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