3

My form has an autofill button that populates some inputs with default information. However, populating the fields does not clear away any validation messages that were already present, unless the user manually clicks over or tabs through the elements. The form will still submit even though the messages are present. Here is the JavaScript that does the populating.

$('#autofillButton').click(function () {
    $('#address').val("localhost");
    $('#port').val("12345");
    $('#receiveTimeout').val("5000");
    $('#sendtimeout').val("5000");
})

Someone suggested adding $("form").validate().resetForm(); to my click function, but that did not work for me. The validation messages remained. Here is a relevant slice of my View.

<p>
    @Html.LabelFor(c => c.address):
    @Html.TextBoxFor(c => c.address)
    @Html.ValidationMessageFor(c => c.address, String.Empty, new { @class ="errorMessage"})
</p>
<p>
    @Html.LabelFor(c => c.port):
    @Html.TextBoxFor(c => c.port)
    @Html.ValidationMessageFor(c => c.port, String.Empty, new { @class ="errorMessage"})
</p>

How can I reset only the validation messages without resetting the entire form?

Roman C
  • 49,761
  • 33
  • 66
  • 176
Rainbolt
  • 3,542
  • 1
  • 20
  • 44

1 Answers1

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();

Option 2:

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

Jason Roell
  • 6,679
  • 4
  • 21
  • 28
  • Similar solutions found here: http://stackoverflow.com/questions/5457393/reset-mvc-form-with-jquery – JSK NS Jan 27 '14 at 20:53
  • Will accept after lunch. +1 for recommending that I go through the generated code in the browser. I get so bogged down in learning MVC that I forget I can do that. – Rainbolt Jan 27 '14 at 20:57
  • Haha I understand. Remember there is no "Magic"! – Jason Roell Jan 27 '14 at 20:58
  • Haha and I like how you eat lunch around 4 o'clock lol. Sounds like when most developers finally get around to eating. Always trying to wait until you get that one last issue worked out... – Jason Roell Jan 27 '14 at 21:03