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

'Like' us on our FaceBook page if you find this blog useful. Thanks!
Did you like this post?
|
|
|
||
|
|
|
|
Save on Delicious |
|
|
subscribe via rss |
|
subscribe via e-mail |
|
|
print this post |
|
follow me on twitter |





comments
3 Responses to "Customize the Display of Error Messages while using the jQuery Validation Plugin"Nice tip.
This is the same technique that the MicrosoftMvcJQueryValidation.js uses in MVC 2 Futures
nice tip here for the coders thanx
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...)
Post a Comment