当与 jQuery Validate 的 submitHandler() 方法一起使用时,DirtyForms 无法正常工作

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

我同时使用 DirtyForms and the popupar jQuery Validate 来验证我的表单。我还需要使用 submitHandler() 方法,因为我在实际发送表单之前执行了一些操作。 在这种情况下,DirtyForms 甚至会在正常的提交表单上触发,而这是不应该的。

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

请问有什么帮助吗?

由于 submitHandler 仅在表单有效时触发,因此您永远不需要 DirtyForms 在这里做任何事情。

所以只需在 submitHandler 内使用 .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();

演示:jsfiddle.net/aunpmfsa/1/