Customize the Display of Error Messages while using the jQuery Validation Plugin

Here’s a simple way to customize the placement of the error labels while using the jQuery Validation Plugin. We will display the error message in a control of our choice, in our case a div called “err”.

I had done a post a couple of days ago showing how to Validate IP Address using jQuery. In this example, when the user entered an invalid IP Address, the error (by default) was displayed in a label control that was placed next to the textbox being validated, as shown below:

image  

We will use the same example, but this time display the error message in a div control. To customize the placement of the error message, we will make use of the jQuery Validation errorPlacement option as shown in the example below:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Validate IP Address using jQuery</title>
<
style type="text/css">
label.error {
float: none; color: red;
padding-left: .3em; vertical-align: top;
}
</style>
<
script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js">
</
script>
<
script
type="text/javascript" src="
http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js">
</
script>
<
script type="text/javascript">
$(function() {
$.validator.addMethod('IP4Checker', function(value) {
var ip = "^(?:(?:25[0-5]2[0-4][0-9][01]?[0-9][0-9]?)\.){3}" +
"(?:25[0-5]2[0-4][0-9][01]?[0-9][0-9]?)$";
return value.match(ip);
}, 'Invalid IP address');

$('#form1').validate({
rules: {
ip: {
required: true,
IP4Checker: true
}
},
errorPlacement: function(error, element) {
error.appendTo('#err');
}
});
});
</script>
</
head>
<
body>
<
form id="form1">
<
input id="ip" name="ip" type="text" />
<
br />
<
div id="err"></div>
<
input id="Submit1" type="submit" value="submit" />
</
form>
</
body>
</
html>

Now when we enter an Invalid IP address and submit the form, the error is placed inside the div as shown below

image



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

3 comments:

Elijah Manor said...

Nice tip.

This is the same technique that the MicrosoftMvcJQueryValidation.js uses in MVC 2 Futures

maddy said...

nice tip here for the coders thanx

da^hype said...

what if the form has more than 1 input box? and i want each error to be posted to its own div? (example #err, #err1, #err2...)