Wednesday 17 December 2014

Clear values of all fields and remove ValidationSummary error messages validation-summary-errors with jquery.

Problem:

I have an ASP.NET MVC 4 application. On several of the pages, I have a "add new item" button relevant to the page. Clicking that button displays a dialog with a form to fill out. The dialog has two buttons, "submit" and "cancel".
Validation of the "Add new item" form is handled in typical MVC style by adding this razor tag just inside the form element:
@Html.ValidationSummary(true)
For the most part, this all works just fine. If a field fails validation, then the submit button causes it to show the validation message.
The problem is this - if the form fails validation, and then the user clicks "cancel", the dialog simply hides itself. The next time "Add new item" is clicked, the dialog appears again, but the validation message is still there from the last failed attempt.
This looks unprofessional. When the user clicks "cancel" the form and the validation should reset.
I am not sure what validation library is being called for validation here. I could always add some javascript to change the CSS of the validation label, etc. but I want to make sure that I'm not breaking the validation, or leaving behind misc javascript, etc.

Answer:

$('.field-validation-error') .removeClass('field-validation-error') .addClass('field-validation-valid').empty();
$('.input-validation-error') .removeClass('input-validation-error') .addClass('valid').empty();