Search code examples
jqueryasp.net-mvcasp.net-mvc-4jquery-validate

Update validation summary in 'real time'


Hi I am using MVC4 with client side validation. This works great for showing validation messages next to the fields.

I have added a validation summary:

 @Html.ValidationSummary(false)

This works, client side 'n all. I would like it to behave differently though; currently the messages in the validation summary only change when the submit button is clicked. I would like them to be dynamically, populated in a similar fashion to each field's validation message.

Can someone suggest a way to achieve this ?

Any information on what triggers the summary update would be great.


Solution

  • I've set up the validation summary to update in 'real time' also considering the following:

    1. Update the summary only once it's visible (after page validate/submit)
    2. Clear the summary when everything is valid

    Let's extract the validator, overrride showErrors() and implement our logic:

    var validator = $('form').data('validator');
    validator.settings.showErrors = function (map, errors) {
        this.defaultShowErrors();
        if ($('div[data-valmsg-summary=true] li:visible').length) {
            this.checkForm();
            if (this.errorList.length)
                $(this.currentForm).triggerHandler("invalid-form", [this]);
            else
                $(this.currentForm).resetSummary();
        }
    }
    

    Since I'm using this solution for my entire site I've created the following init (onready):

    $('form').each(function () {
        var validator = $(this).data('validator');
        if (validator) {
            validator.settings.showErrors = function (map, errors) {
                this.defaultShowErrors();
                if ($('div[data-valmsg-summary=true] li:visible').length) {
                    this.checkForm();
                    if (this.errorList.length)
                        $(this.currentForm).triggerHandler("invalid-form", [this]);
                    else
                        $(this.currentForm).resetSummary();
                }
            };
        }
    });
    

    And here's the resetSummary used above:

    jQuery.fn.resetSummary = function () {
        var form = this.is('form') ? this : this.closest('form');
        form.find("[data-valmsg-summary=true]")
            .removeClass("validation-summary-errors")
            .addClass("validation-summary-valid")
            .find("ul")
            .empty();
        return this;
    };