Clear/Reset MVC 3 Form and Unobtrusive jQuery Client Validation

Intro

So today I needed to clear a MVC 3 form  with unobtrusive client validation applied to it via jquery.validate.js & jquery.validate.unobtrusive.js. This doesn’t seem too tricky initially until I realized that doing a form reset via a <input type=”reset”/> or a javascript form.Reset() doesn’t eliminate any jQuery validation messages that were displayed! Take a look below at a weird looking example form below where I did this:

  • Entered a user name
  • Clicked “LOGIN”
  • JavaScript presented me with errors indicating a password is required
  • Clicked “RESET”

actual-behavior

I would expect the form to look more like this after clicking “RESET”, basically reset the form to it’s initial state:

desired-behavior

Solution, Basic Example

I did some digging online and didn’t find any satisfying answers to this question so I wrote two jQuery plugins that either clear validation, reset the form (for use with NON input type=submit) or do both. Here’s some basic examples:

 

<!--Clear validation and the form from:-->

<!-- an "a" link -->
<a onclick="$(this).formReset(); return false;">Reset</a>

<!-- a reset input, this handles the the form reset but not validation clearing-->
<input onclick="$(this).resetValidation()" type="reset" value="Reset" />

 

 

Solution, Better Example

Of course instead of having inline “onclick”s you could put a live handler in a core JS file to get this sort of behavior across a whole site. Also note for this example you would need to have a class of “form-reset” on any form resetting elements (not a reset input though):

 

$(function () {
      $('.form-reset').live('click', function () {
          $(this).formReset();
          return false;
      });

      $('input[type=reset]').live('click', function () {
          $(this).resetValidation();
      });
})

 

 

Here are the same HTML examples with the above live handler (a bit cleaner):

 

<!--Clear validation and the form from:-->

<!-- an "a" link -->
<a class='form-reset'>Reset</a>

<!-- a reset input, this handles the the form reset but not validation clearing-->
<input type="reset" value="Reset" />

 

The jQuery Plugin

Finally here is the required jQuery plugin code for it all to work:

 

(function ($) {

    //re-set all client validation given a jQuery selected form or child
    $.fn.resetValidation = function () {

        var $form = this.closest('form');

        //reset jQuery Validate's internals
        $form.validate().resetForm();

        //reset unobtrusive validation summary, if it exists
        $form.find("[data-valmsg-summary=true]")
            .removeClass("validation-summary-errors")
            .addClass("validation-summary-valid")
            .find("ul").empty();

        //reset unobtrusive field level, if it exists
        $form.find("[data-valmsg-replace]")
            .removeClass("field-validation-error")
            .addClass("field-validation-valid")
            .empty();

        return $form;
    };

    //reset a form given a jQuery selected form or a child
    //by default validation is also reset
    $.fn.formReset = function (resetValidation) {
        var $form = this.closest('form');

        $form[0].reset();

        if (resetValidation == undefined || resetValidation) {
            $form.resetValidation();
        }

        return $form;
    }
})(jQuery);

 

 

Enjoy! Hopefully this makes working with jQuery Unobtrusive Validation a bit easier.

14 thoughts on “Clear/Reset MVC 3 Form and Unobtrusive jQuery Client Validation

  1. Hi Please check this code.

    this code would be work for any page, code will clear html control as well as jquery error message

    /******************************************Clear form elements**********************************************************/
    function clear_form_elements(ele) {

    $(ele).find(‘:input’).each(function() {
    switch(this.type) {
    case ‘password’:
    case ‘select-multiple’:
    case ‘select-one’:
    case ‘text’:
    case ‘textarea’:
    $(this).val(”);
    break;
    case ‘checkbox’:
    case ‘radio’:
    this.checked = false;
    }
    });

    $(‘input[type=button]’).live(‘click’, function () {
    $(this).resetValidation();
    });
    }
    /*******************************************helping method for clearing form- clear jquery validation error*************/

    (function ($) {

    //re-set all client validation given a jQuery selected form or child
    $.fn.resetValidation = function () {

    var $form = this.closest(‘form’);

    //reset jQuery Validate’s internals
    $form.validate().resetForm();

    //reset unobtrusive validation summary, if it exists
    $form.find("[data-valmsg-summary=true]")
    .removeClass("validation-summary-errors")
    .addClass("validation-summary-valid")
    .find("ul").empty();

    //reset unobtrusive field level, if it exists
    $form.find("[data-valmsg-replace]")
    .removeClass("field-validation-error")
    .addClass("field-validation-valid")
    .empty();

    return $form;
    };

    //reset a form given a jQuery selected form or a child
    //by default validation is also reset
    $.fn.formReset = function (resetValidation) {
    var $form = this.closest(‘form’);

    $form[0].reset();

    if (resetValidation == undefined || resetValidation) {
    $form.resetValidation();
    }

    return $form;
    }
    })(jQuery);

    /****************************************************************************************************************/

    [b]Copy and paste this code in your javascript file and call the method on button click event[/b]

    <input id="Cancel" onclick="clear_form_elements(this.form)" type="button" value="Cancel" />

  2. hi! , Everyone loves a persons writing quite definitely! promote many of us keep up a correspondence more info on your own document for Yahoo? I need a pro for this dwelling to unravel this dilemma. Could be that is definitely a person! Looking forward to search an individual. cbggfkgceddg

  3. Tried every other solution. Calling $form.validate().resetForm(); alone wouldn’t clear the error messages. We have to remove the errors too. This worked perfectly! Thank you!

Leave a Reply

Your email address will not be published. Required fields are marked *

Proudly powered by WordPress | Theme: Cute Blog by Crimson Themes.