1

I'm having a bit of trouble with the client-side validation in the ASP.NET MVC 2 framework and hope someone can help me out.

In several situations I find it useful to be able to reset the contents of a form or just a single input element and I need any validation errors to disappear. This in itself is not very hard, and the suggestion provided here works well enough: How do I clear MVC client side validation errors when a cancel button is clicked when a user has invalidated a form?

The problem is that, when triggered, client validation goes into an aggressive mode that performs validation on each key press and when an input loses focus. Is there a good way to reset this state as well?

Community
  • 1
  • 1
Morten Christiansen
  • 19,002
  • 22
  • 69
  • 94

1 Answers1

3

It turned out that some of my problems could be solved by setting the reset button to type reset which the validation framework respects. This doesn't work when a failed submit occurs (due to invalid fields) and in this case I ended up using the following function (selector is a jQuery selector string):

resetFieldValidation: function (selector) {
    var fields = $(selector);
    fields.removeClass('input-validation-error').addClass('input-validation-valid');
    fields.siblings('.field-validation-error').text('').removeClass('field-validation-error').addClass('field-validation-valid');
    fields.each(function () {
        $(this)[0]['__MVC_HasTextChanged'] = false;
        $(this)[0]['__MVC_HasValidationFired'] = false;
    });
}

The last part of the function sets values indicating to the validation framework that the fields have not changed and have not previously triggered a validation error.

Morten Christiansen
  • 19,002
  • 22
  • 69
  • 94