How do I clear MVC client side validation errors when a cancel button is clicked when a user has invalidated a form?
Asked Answered
P

9

37

I have a partial view that is rendered within a main view. The partial view takes advantage of System.ComponentModel.DataAnnotations and Html.EnableClientValidation().

A link is clicked, and div containing the partial view is displayed within a JQuery.Dialog().

I then click the save button without entering any text in my validated input field. This causes the client side validation to fire as expected, and display the '*required' message beside the invalid field.

When the cancel button is clicked, I want to reset the client side MVC validation back to it's default state and remove any messages, ready for when the user opens the dialog again. Is there a recommended way of doing this?

Petrolatum answered 9/5, 2010 at 17:3 Comment(1)
Clicking the Cancel button should dismiss the JQuery Dialog, which would require you to construct a new one when the user clicks the Edit button. At that point, the MVC validation should already be at its default state. If it's not (i.e. the underlying DOM objects associated with the dialog still contain data from the last Dialog call), the proper way is to simply clear the values from the DOM objects.Heulandite
G
54

This answer is for MVC3. See comments below for help updating it to MVC 4 and 5

If you just want to clear the validation-messages so that they are not shown to the user you can do it with javascript like so:

function resetValidation() {
        //Removes validation from input-fields
        $('.input-validation-error').addClass('input-validation-valid');
        $('.input-validation-error').removeClass('input-validation-error');
        //Removes validation message after input-fields
        $('.field-validation-error').addClass('field-validation-valid');
        $('.field-validation-error').removeClass('field-validation-error');
        //Removes validation summary 
        $('.validation-summary-errors').addClass('validation-summary-valid');
        $('.validation-summary-errors').removeClass('validation-summary-errors');

    }

If you need the reset to only work in your popup you can do it like this:

function resetValidation() {
        //Removes validation from input-fields
        $('#POPUPID .input-validation-error').addClass('input-validation-valid');
        $('#POPUPID .input-validation-error').removeClass('input-validation-error');
        //Removes validation message after input-fields
        $('#POPUPID .field-validation-error').addClass('field-validation-valid');
        $('#POPUPID .field-validation-error').removeClass('field-validation-error');
        //Removes validation summary 
        $('#POPUPID .validation-summary-errors').addClass('validation-summary-valid');
        $('#POPUPID .validation-summary-errors').removeClass('validation-summary-errors');

    }

I hope this is the effect you seek.

Gord answered 11/5, 2010 at 10:26 Comment(4)
Thanks for your response. I had implemented a similar solution, but it exposes an additional problem, that when the cancel button is clicked, the textbox looses focus, and fires the validation again! You end up seeing the error message appear before the dialog is closed. The only way I may end up solving this problem is by injecting the dialog into the div using a JQuery.Ajax call to get the partial view into the DIV used by the popup. This way, when the dialog is closed, the 'persistance' is lost.Petrolatum
Couldn't you remove focus from the textbox before you call the "reset"-function? Or am I missing something in your setup?Gord
I used this method in an MVC 4 app, but it left the validation errors displayed. Adding $('.validation-summary-errors li').remove(); to the top of the method fixed that issue.Fovea
In MVC5 validation message text was still displayed, so I had to clear with $('.field-validation-error').text('');Hosbein
R
20

If you are using unobtrusive validation that comes with MVC you can simply do:

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

------------------------------------------------------------------------

Third Party Edit: This mostly worked in my case, but I had to remove the $(this).find(".field-validation-error").empty(); line. This appeared to affect the re-showing of the validation messages when resubmitting.

I used the following:

$.fn.clearErrors = function () {
        $(this).each(function() {
            $(this).trigger('reset.unobtrusiveValidation');
        });
    };

and then called it like this:

$('#MyFormId input').clearErrors();
Ramunni answered 23/4, 2013 at 9:32 Comment(1)
Can we just clear validation error for a specific input (based on id for example) instead of all the inputs?Thrippence
L
10
function resetValidation() {

    $('.field-validation-error').html("");

} 
Labor answered 17/6, 2016 at 8:55 Comment(0)
S
3

You can simply define a new function in jQuery:

$.fn.resetValidation = function () {
    $(this).each(function (i, e) {
        $(e).trigger('reset.unobtrusiveValidation');
        if ($(e).next().is('span')) {
            $(e).next().empty();
        }
    });
};

and then use it for your input fields:

$('#formId input').resetValidation();
Sparhawk answered 29/7, 2018 at 5:52 Comment(0)
S
1

Thank you. I had a similar question for a slightly different scenario. I have a screen where when you click one of the submit buttons it downloads a file. In MVC when you return a file for download, it doesn't switch screens, so any error messages which were already there in the validation summary remain there forever. I certainly don't want the error messages to stay there after the form has been submitted again. But I also don't want to clear the field-level validations which are caught on the client-side when the submit button is clicked. Also, some of my views have more than one form on them.

I added the following code (thanks to you) at the bottom of the Site.Master page so it applies to all of my views.

    <!-- This script removes just the summary errors when a submit button is pressed 
    for any form whose id begins with 'form' -->
<script type="text/javascript">
    $('[id^=form]').submit(function resetValidation() {
        //Removes validation summary
        $('.validation-summary-errors').addClass('validation-summary-valid');
        $('.validation-summary-errors').removeClass('validation-summary-errors');
    });
</script>

Thanks again.

Sacristan answered 5/4, 2011 at 16:4 Comment(1)
It's now a year later and I upgraded the project to VS 2010, MVC3 and Razor. For some reason MVC3 no longer puts "id='form0'" tag when using HTML.BeginForm() helper function by default. You would have to do a new { id = 'form0" } in every Html.BeginForm(). Or you have to set ClientValidationEnabled to true and set UnobtrusiveJavaScriptEnabled to false. What I ended up doing is modify the jQuery selector to just work for any form tag as follows "$('form').submit(function resetValidation() {"Sacristan
A
1

You can tap into the validation library methods to do this. There are two objects of interest: FormContext and FieldContext. You can access the FormContext via the form's __MVC_FormValidation property, and one FieldContext per validated property via the FormContext's fields property.

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.length; i++) {
    var fieldContext = fieldContexts[i];
    // Clears validation message
    fieldContext.clearErrors();
}
// Clears validation summary
form.__MVC_FormValidation.clearErrors();

Then, you can hook that piece of code to whichever event you need.

Sources for this (quite undocumented) insight:

Antiparticle answered 5/1, 2012 at 13:35 Comment(0)
B
1

In order to complete clear the validation artifacts including the message, the coloured background of the input field, and the coloured outline around the input field, I needed to use the following code, where this was (in my case) a Bootstrap modal dialog containing an imbedded form.

$(this).each(function () {
    $(this).find(".field-validation-error").empty();
    $(this).find(".input-validation-error").removeClass("input-validation-error");
    $(this).find(".state-error").removeClass("state-error");
    $(this).find(".state-success").removeClass("state-success");
    $(this).trigger('reset.unobtrusiveValidation');
});
Bopp answered 12/8, 2017 at 22:44 Comment(0)
P
0

Here you can use simply remove error message

$('.field-validation-valid span').html('')

OR

  $('.field-validation-valid span').text('')

enter image description here

Population answered 1/11, 2017 at 18:0 Comment(0)
O
0

I've this issue for "Validation summery" after form ajax submit and done it like this:

        $form.find('.validation-summary-errors ul').html('');

and complete code is:

$("#SubmitAjax").on('click', function (evt) {
    evt.preventDefault();
    var $form = $(this).closest('form');
    if ($form.valid()) {

        //Do ajax call . . .

        //Clear validation summery
        $form.find('.validation-summary-errors ul').html('');
    }
});
Olenolin answered 24/10, 2021 at 10:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.