Introduction
ASP.NET MVC handles a lot of things out of the box; one of
these features is validation. ASP.NET MVC (3 onwards) provides client side validation
capabilities using Microsoft unobtrusive adapter for jQuery validation (jquery.validate.unobtrusive.js).
MVC embeds the meta-data information and embeds it into data-val tags in
the generated markup. The adapter will go through the markup, find the validation
tags and enforce them through jQuery validation plugin. Unfortunately, doing
this means that some of the control is lost as the validator is initialized
internally for each form.
Problem
One such problem I faced recently was to try and hook into submit
and invalid events raised by JQuery validation. This means that doing something
like this in our start up code (jQuery ready event) has no effect:
$("form").validate({
submitHandler: function (form) {
form.submit();
},
invalidHandler: function (form, validator)
{
alert('error');
}
})
The workaround is kind of simple. I was first alerted when I
was debugging the validate method in jquery.validate.js:
var validator = $.data(this[0], 'validator');
if ( validator ) {
return validator;
}
The solution is to retrieve the validator settings object
and then set its properties.
var settings = $.data($('form')[0], 'validator').settings;
settings.submitHandler= function(form) {
if (confirm("Are you sure you wish to submit"))
form.submit();
};
The second issue was to display a message in case the
validation failed. On first glance this code should work,
settings.invalidHandler = function (form) {
alert("invalid");
};
However it doesn't. Further investigation of jquery.validate.js
revealed the following line:
if (this.settings.invalidHandler)
$(this.currentForm).bind("invalid-form.validate", this.settings.invalidHandler);
So in order to have a call back when invalid form is
submitted, the proper approach is bind to the invalid-form.validate event.
Here is my final method that displays the list of errors:
$("form").bind("invalid-form.validate", function (form,validator) {
var errors = validator.numberOfInvalids();
var message = "Please fix" + errors + " errors.";
for (var x=0;x<validator.errorList.length;x++)
{
message += "<br/>\u25CF" + validator.errorList[x].message;
}
$("#errorList").html(message);
$("#errorList").slideDown('fast');
});
The final code is below:
$(document).ready(function () {
var settings = $.data($('form')[0], 'validator').settings;
$("form").bind("invalid-form.validate", function (form,validator) {
var errors = validator.numberOfInvalids();
var message = "Please fix" + errors + " errors.";
for (var x=0;x<validator.errorList.length;x++)
{
message += "<br/>\u25CF " + validator.errorList[x].message;
}
$("#errorList").html(message);
$("#errorList").slideDown('fast');
});
settings.submitHandler = function (form) {
if (confirm("Are you sure you wish to submit"))
form.submit();
};
});
References
The following posts were used as reference:
History
- 03-01-2013: First version.