Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 849
StanK Avatar asked Mar 06 '11 22:03

StanK


People also ask

What is unobtrusive validation in MVC?

An unobtrusive validation in jQuery is a set of ASP.Net MVC HTML helper extensions.By using jQuery Validation data attributes along with HTML 5 data attributes, you can perform validation to the client-side.

What is validation summary in MVC?

Implementation Details. Main Features. ValidationSummary is an extension that allows you to summarize validation errors from multiple data editors.

What is validator unobtrusive parse?

validator. unobtrusive. parse(selector) method to force parsing. This method parses all the HTML elements in the specified selector and looks for input elements decorated with the [data-val=true] attribute value and enables validation according to the data-val-* attribute values.


1 Answers

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();
        }
    } 
});
like image 143
Todd Horst Avatar answered Oct 04 '22 02:10

Todd Horst