10

In my asp.net mvc page I need to have a "clear" button that resets certain input fields and clears all the error messages. Clearing the inputs is fine but because the validation messages are generated by the asp.net mvc javascript it's not obvious to me how to clear them?

Update: This ended up working well for me.

$(".field-validation-error").empty();
sipsorcery
  • 30,273
  • 24
  • 104
  • 155
  • Is it the server-side error messages you'd like to clear? – Nathan Taylor Jan 24 '11 at 22:54
  • I thought they were generated client side but I just hooked up fiddler and they are generated server side after all. It'd be nice if I could still remove them by pressing a button on the client without requiring a re-submit. – sipsorcery Jan 24 '11 at 23:07

4 Answers4

5

You can view the html code generated in the browser and then just empty it through jquery e.g. empty()

To find the generated code:

  • Normal postback: view the page's "source code" in the browser and look for the error message. Find the parent div to empty it.
  • Ajax call: right click and inspect elements in Chrome (other modern browsers call it differently but they should have the tool). This will give you the html generated at the current state (after the ajax call). Find the parent div and empty it.

Hope this helps

Mouhannad
  • 2,209
  • 1
  • 14
  • 12
3
$('.field-validation-error').text("")
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
2

A simple and reusable jQuery function you can call on any jQuery object:

$.fn.clearErrors = function () {
    $(this).each(function() {
        $(this).find(".field-validation-error").empty();
        $(this).trigger('reset.unobtrusiveValidation');
    });
};

Usage:

question.clearErrors();

Original answer: https://stackoverflow.com/a/16165831/114029

Community
  • 1
  • 1
Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
0

Having a reset input button could help, but it only resets the form back to its state when the form was loaded.

When I want to reset all the values, I usually disguise a hyperlink as a reset button. When someone clicks it, it just does a new GET request for the form. Since the controller action for a GET request just returns a brand new empty model, it has the same effect as a "clear" button.

danludwig
  • 46,965
  • 25
  • 159
  • 237