Click here to Skip to main content
Click here to Skip to main content

Modify jQuery validation settings using MVC unobtrusive validation

, 3 Feb 2013
Rate this:
Please Sign up or sign in to vote.
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: 

//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:

//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.

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.

License

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

Share

About the Author

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

Comments and Discussions

 
GeneralMy vote of 5 Pinmemberkhoa_chung_8931-Mar-14 8:41 
GeneralThanks PinmemberRetroSonic17-Dec-13 7:26 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140827.1 | Last Updated 3 Feb 2013
Article Copyright 2013 by Talal Tayyab
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid