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 开发者_如何学JAVAwould 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
.
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();
}
}
});
You can setup the validation summary to be triggered a lot more often, in onready:
var validator = $('form').data('validator');
validator.settings.showErrors = function (map, errors) {
this.defaultShowErrors();
this.checkForm();
if (this.errorList.length)
$(this.currentForm).triggerHandler("invalid-form", [this]);
else
$(this.currentForm).resetSummary();
}
}
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;
};
I have a similar question open here: How to display MVC 3 client side validation results in validation summary but the suggested solution by Darin does not seem to work the way I (and probably you) want it to.
精彩评论