jqueryjquery-validatejquery-dirtyforms

DirtyForms does not work properly when used with submitHandler() method of jQuery Validate


I'm using both DirtyForms and the popupar jQuery Validate to validate my forms. I also need to use the submitHandler() method because I do a couple of actions before actually sending the form. In this scenario, DirtyForms is triggered even on a normal submit form, when it shouldn't be.

$('.validate').validate({
	// submitHandler causer DirtyForms to be triggered evn on normal form submit
  submitHandler: function (form) {
    // do a couple of things here, then...
    form.submit();
  }
});

$('form[method="post"]').dirtyForms();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.dirtyforms/2.0.0/jquery.dirtyforms.min.js"></script>

<p>Fill the field and send the form, you'll see that DirtyForms is triggered even if it should not</p>
<form action="#" method="post" class="validate">
  <input type="text" name="username" required>
  <button type="submit">send</button>
</form>

Please, any help?


Solution

  • Since submitHandler only fires when the form is valid, you will never need DirtyForms to do anything here.

    So just kill it within submitHandler using .dirtyForms('setClean')

    $('.validate').validate({
        submitHandler: function(form) {
            // do a couple of things here, then...
            $('form:dirty').dirtyForms('setClean');  // <- kill DirtyForms
            form.submit();
        }
    });
    
    $('form[method="post"]').dirtyForms();
    

    DEMO: jsfiddle.net/aunpmfsa/1/