asp.net mvc 3 validation summary not showing via unobtrusive validation

StanK picture StanK · Mar 6, 2011 · Viewed 9.6k times · Source

I'm having problems getting the asp.net MVC client-side validation to work how I want it.

I have it basically working, however, the validation summary is not displayed until the user clicks the submit button, even though the individual inputs are being highlighted as invalid as the user tabs/clicks etc their way through the form. This is all happening client-side.

I would have thought the that the validation summary would be displayed as soon as an input field was discovered that was invalid.

Is this behaviour by design? Is there any way around it, as I would like the validation summary to be displayed as soon as it is discovered that one of the input fields is invalid.

My code is basically,

<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
...
    @using (Html.BeginForm())
    {
        @Html.ValidationSummary(false)
        @Html.EditorFor(model => model);   
        ...

And my _Layout.cshtml references jquery-1.4.4.min.js.

Answer

Todd Horst picture Todd Horst · May 23, 2013

I used a version of Torbjörn Nomells answer

Except here I hang resetSummary off the validator object

$.validator.prototype.resetSummary= function () {
    var form = $(this.currentForm);
    form.find("[data-valmsg-summary=true]")
        .removeClass("validation-summary-errors")
        .addClass("validation-summary-valid")
        .find("ul")
        .empty();
    return this;
};

Then change calling it to

$.validator.setDefaults({
    showErrors: function (errorMap, errorList) {
        this.defaultShowErrors();
        this.checkForm();
        if (this.errorList.length) {
            $(this.currentForm).triggerHandler("invalid-form", [this]);
        } else {
            this.resetSummary();
        }
    } 
});