0

I have a very simple issue: There is a form with a clear form button. When I click on it, all fields reset. But I also have an extra validation rule: at least one additional field should be filled. After clearing, they all are empty, of course, but I don't want to see these validation messages. I want it to clear the entire form, hide all validation messages and so on. Here is my code:

$("a[data-clear]").click(function (event) {
    var now = new Date();
    $("#report_search section:gt(0) input").val("");
    $("#includeDerived").prop("checked", true);
    $("#includeApp").prop("checked", true);
    $("#includeOrg").prop("checked", false);
    $("input[name='FromDate']").datepicker().datepicker("setDate", now.dateAdd("year", -1));
    $("input[name='ToDate']").datepicker().datepicker("setDate", now);
    $("form").validate().resetForm();
    event.preventDefault();
});

I have only one form on the page so multiple forms is not an issue.

Desired result: form is cleared, validation messages are not shown.

Actual result: form is cleared, validation messages persist.


Sample rule which is checking if fields are filled:

jQuery.validator.addMethod("isSufficientInfo",
    function (value, element, params) {
        var hasPersonInfo = $("input[name='LastName']").val() && $("input[name='FirstName']").val();
        if (hasPersonInfo) {
            return true;
        }
        var hasDocInfo = $("select[name='D']").val() && $("input[name='C']").val() && $("input[name='E']").val();
        if (hasDocInfo) {
            return true;
        }
        return $("input[name='A']").val() || $("input[name='B']").val();
    }, "File some fields");
$("#IsEnoughInfo").rules("add", { isSufficientInfo: "" });
Alex Zhukovskiy
  • 9,565
  • 11
  • 75
  • 151
  • It looks like this doesn't work with Bootstrap 3 (if you're using that). Either way, you could simply hide the errors by removing the error class until you validate again. [How to clear Jquery validation error messages](http://stackoverflow.com/questions/2086287/how-to-clear-jquery-validation-error-messages) – Michael Armes Sep 28 '16 at 17:38
  • 1
    you are getting error message because of this `$("form").validate().resetForm();` line which runs your validation and generates error message. You will have to override logic to verify the validation in validator's [submitHandler](https://jqueryvalidation.org/validate/#submithandler) for your custom logic. – Samundra Sep 28 '16 at 18:07
  • 1
    @MeghanArmes I'm not using bootstrap in this project. I defenitly can just clear html in `.field-validation-error` fields, but it looks very hacky. I assumed there is some proper way to do it. – Alex Zhukovskiy Sep 28 '16 at 18:15
  • @AlexZhukovskiy I agree it's a hacky way to do things, definitely. – Michael Armes Sep 28 '16 at 18:16
  • @Samundra I just want to hide all errors for all currently binded rules. I don't want to override any logic. For example I had 10 fields with 10 errors. When I click on `clear` all these fields should be cleared, and error messages should dissapear. It works when I run `('form').valid()`, but it also cause validation rule `at least one field should be non-empty` to fire. – Alex Zhukovskiy Sep 28 '16 at 18:17
  • @MeghanArmes ok, now I am using `$(".field-validation-error").html("").removeClass("field-validation-error")`, but I'm still looking for more adequate solution. – Alex Zhukovskiy Sep 28 '16 at 18:19
  • 1
    If you are using the same library which I mentioned then you might want to look at [resetForm](https://jqueryvalidation.org/Validator.resetForm/) API call. – Samundra Sep 28 '16 at 18:20
  • @Samundra If you read my question, I write that I used that API but it didn't work. You can also see this call in my sample code. – Alex Zhukovskiy Sep 28 '16 at 18:21
  • My bad I missed the title, you may want to see how `resetElements` work and try to do something similar see [resetElements](https://github.com/jzaefferer/jquery-validation/blob/master/src/core.js#L515-L544) – Samundra Sep 28 '16 at 18:24
  • 1
    I think this [https://jsfiddle.net/1u0tccgg/](https://jsfiddle.net/1u0tccgg/) describes your problem more clearly. – Samundra Sep 28 '16 at 18:45

2 Answers2

2

If you're still looking for the answer, I suspect that $("form").validate() creates a new validator instance. What you need is the previously created instance:

$("form").data("validator").resetForm()

Or store the validator in a variable:

var v = $("form").validate()
v.resetForm()
Pete rudensky
  • 404
  • 1
  • 5
  • 9
  • 1
    How is this the answer? Isn't this what you said is not working? `$("form").validate() only creates a new validator if one doesn't already exist. – xr280xr Aug 31 '17 at 23:45
1

Reason for error

Your event for click event is getting propagated from button to window (inside-out). This is causing your form to trigger validation and thus you are getting the same error message, even after you call the resetForm. If you debug the validation library step by step and get to this.hideErrors then you will see that when this.hideErrors gets executed, the error messages are gone. Since the validation script hasn't finished yet, it continues with other statements, and at the end the event that got propagated is handled by the window from inside-out. The error messages are again shown as this event triggers the request on the form.

Solution

The solution is to move your call to event.preventDefault() to the top, like as shown below:

$("a[data-clear]").click(function (event) {
    event.preventDefault(); // Move to top

    var now = new Date();
    $("#report_search section:gt(0) input").val("");
    $("#includeDerived").prop("checked", true);
    $("#includeApp").prop("checked", true);
    $("#includeOrg").prop("checked", false);
    $("input[name='FromDate']").datepicker().datepicker("setDate", now.dateAdd("year", -1));
    $("input[name='ToDate']").datepicker().datepicker("setDate", now);

    $("form").validate().resetForm(); // this should work now
});

Also see the updated jsfiddle sample

Give it a try and let me know if this works for you or not. I did the step-by-step debug and got to this conclusion.

Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58
Samundra
  • 1,869
  • 17
  • 28
  • No, it's not working in my case. `validator` doesn't see any errors at all (when I debugged I found that `this.errors()` is always empty). The only method which is working as expected is `valid()`. But as I said it doesn't hide the last check (which I add in my question). See link on jsfiddle of @Samundra above – Alex Zhukovskiy Sep 28 '16 at 20:18
  • That's weird maybe you should also add your form. – Samundra Sep 28 '16 at 20:42