Click here to Skip to main content
15,884,237 members
Articles / Web Development / ASP.NET
Tip/Trick

Modify jQuery validation settings using MVC unobtrusive validation

Rate me:
Please Sign up or sign in to vote.
4.89/5 (6 votes)
3 Feb 2013CPOL1 min read 58.3K   13   3
ASP.NET MVC 4 unobtrusive validation - Event hooks.

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: 

C#
//will not work if using MVC JQuery Unobtrusive validation
$("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:

C#
//check if a validator for this form was already created
var validator = $.data(this[0], 'validator'); 
if ( validator ) {
return validator;
} 

The solution is to retrieve the validator settings object and then set its properties.

C#
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,

C#
settings.invalidHandler = function (form) {
	alert("invalid");
};  

However it doesn't. Further investigation of jquery.validate.js revealed the following line:

C#
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: 

C#
$("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: 

C#
$(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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Australia Australia
A seasoned software engineer with over 13 years of commercial experience in software design/development.

Comments and Discussions

 
PraiseThanks Pin
Darius Lukauskas1-Apr-16 3:50
Darius Lukauskas1-Apr-16 3:50 
GeneralMy vote of 5 Pin
khoa_chung_8931-Mar-14 8:41
khoa_chung_8931-Mar-14 8:41 
GeneralThanks Pin
RetroSonic17-Dec-13 7:26
RetroSonic17-Dec-13 7:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.