How to Reset Form Unobtrusive jQuery?

I was looking around for a way to reset a form that was already validated by Unobtrusive jQuery Client Validation. JQuery validate doesn’t have any way to reset the UI after errors occur. However, you can safely use:

var validator = $( "#myform" ).validate();
validator.resetForm();

The best example I found online was on John Culviner blog. It wasn’t exactly what I was looking for, but it was a good start. He resets the form by using a button and attributes, I need a function that does that, so I create a plugin that clears the form on demand.

Clear Reset Form Unobtrusive jQuery validation part 2

usage: $(“#signupform”).clearForm()

(function ($) {

    $.fn.clearForm = function (options) {

        // This is the easiest way to have default options.
        var settings = $.extend({
            // These are the defaults.

            formId: this.closest('form')

        }, options);

        var $form = $(settings.formId);

        //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;
    };

}(jQuery));

Good luck on your adventure! This should help a few people using unobtrusive Validation with MVC3.

Posted in: Inspiration

Tagged as: , , ,

Advertisements

2 thoughts on “How to Reset Form Unobtrusive jQuery? Leave a comment

  1. What’s up, I log on to your blogs daily. Your story-telling style is witty, keep up the good work!

  2. πŸ‡ Support The Blog πŸ“’

    Please continue to scroll down to comment or see below.

    🐰 If you do decide to buy something, I’ll get some commission, and you’ll get a chance to support me. Thank you for those that do buy via my links. πŸ’ž

What’s Crackin’ \ (β€’β—‘β€’) /

This site uses Akismet to reduce spam. Learn how your comment data is processed.