Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear ASP.Net MVC validation messages with jQuery

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();
like image 445
sipsorcery Avatar asked Jan 24 '11 22:01

sipsorcery


People also ask

How remove validation message after field is valid in MVC?

So, to clear the validation errors, you can do something like this to a form : var fieldContexts = form. __MVC_FormValidation. fields; for(i = 0; i < fieldContexts.

How remove validation message after field is valid?

Adding an else statement to return the value of your error message span to a non-error state could correct this. this should display your error msg and return it to blank when a valid input is present.


3 Answers

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

like image 160
Mouhannad Avatar answered Sep 19 '22 18:09

Mouhannad


$('.field-validation-error').text("")
like image 31
Gurpreet Singh Avatar answered Sep 18 '22 18:09

Gurpreet Singh


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

like image 38
Leniel Maccaferri Avatar answered Sep 19 '22 18:09

Leniel Maccaferri