Validation with jQuery validator plugin
Reference
http://docs.jquery.com/Plugins/Validation/
Setup
A reference to jQuery validator plugin
<script type=”text/javascript” src=”http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.js”></script>
A reference to jQuery
<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js”></script>
Configuration – simple on class and attribute level
It is possible to declare your validation rules in various ways. It is suggested primarily to try it on class and attribute level and secondary using dependency-callback.
Example class and attribute rules:
<input id=”cemail” name=”email” size=”25″ class=”required email” minlength=”2″ title=”Required or not correct format.” />
/* this would check that email is entered, that at least 2 characters are typed and also that email validation rule */
The validation on the form is registered by
<script>
$(document).ready(function(){
$(“#aspnetForm”).validate();
});
</script>
A list of available validators can be found here http://docs.jquery.com/Plugins/Validation/#List_of_built-in_Validation_methods
There are also custom validation rules that can be implemented by including additional-methods.js (when you download the plugin validation package).
If you don’t specify any validation messages you will get standard validation messages so it would be a nice thing to specify your own. The title attribute is available for a standard message, however if you need to customize the message for each different type of validation error, check later advanced topic on how to customization validate()
Configuration – custom messages
To specify your own messages you pass it into your form validation rules
The validation on the form is changed to
<script>
$(document).ready(function(){
$(“#aspnetForm”).validate(
{
messages: {
email: {
required: “We need your email address to contact you”,
email: “Your email address must be in the format of name@domain.com”,
minlength: jQuery.format(“At least {0} characters required!”)
}
}
}
);
});
</script>
Configuration – specify rules for validate()
It is possible to define your own rules by sending on more options for validate()
Example class and attribute rules:
<input id=”cemail” name=”email” size=”25″ />
/* notice that we now removed the class and attribute rules from the input element */
The validation on the form is then changed to use
<script>
$(document).ready(function(){
$(“#aspnetForm”).validate(
{
rules: {
email: {
required: true,
email: true,
minlength: 2
}
},
messages: {
email: {
required: “We need your email address to contact you”,
email: “Your email address must be in the format of name@domain.com”,
minlength: jQuery.format(“At least {0} characters required!”)
}
}
}
);
});
</script>
Configuration – validation using dependency expression
It is possible to define limit validation for a specific expression (such as #object:checked, #object:filled, #object.visible)
The validation on the form is then changed to use
<script>
$(document).ready(function(){
$(“#aspnetForm”).validate(
{
rules: {
email: {
required: “#identifyofmycheckbox:checked”,
email: true,
minlength: 2
}
},
messages: {
email: {
required: “We need your email address to contact you”,
email: “Your email address must be in the format of name@domain.com”,
minlength: jQuery.format(“At least {0} characters required!”)
}
}
}
);
});
</script>
Configuration – validation using dependency callback
It is possible to define limit validation using your own functions. This enables even more complex checks such as ajax-calls to perform server side checks.
The validation on the form is then changed to use
<script>
$(document).ready(function(){
$(“#aspnetForm”).validate(
{
rules: {
email: {
required: function(element) {
return getValidationIsEmailNeededFromServer();
},
email: true,
minlength: 2
}
},
messages: {
email: {
required: “We need your email address to contact you”,
email: “Your email address must be in the format of name@domain.com”,
minlength: jQuery.format(“At least {0} characters required!”)
}
}
}
);
});
</script>
It is also possible to use the addMethod() to register any custom checks to the validator
<script>
$(document).ready(function(){
$(“#aspnetForm”).validate(
{
rules: {
email: {
required: true,
email: true,
minlength: 2,
duplicate: true
}
},
messages: {
email: {
required: “We need your email address to contact you”,
email: “Your email address must be in the format of name@domain.com”,
minlength: jQuery.format(“At least {0} characters required!”)
}
}
}
);
});
jQuery.validator.addMethod(“duplicate”, function(value, element, params) {
return checkUniqueEmail(value) {
}, jQuery.format(“Email is not unique.”));
</script>
Placement of errors
By default jQuery validator injects the error messages just next to the control that does not validate. It also adds an error class on each element that does not validate. Therefore it is easy to style elements and give an invalid <input> element a red border when it is invalid.
<style type=”text/css”>
input.error { border: 1px solid red; }
input.error:focus { border: 1px solid red; }
</style>
If you want to override the placement of errors next to your invalid control you can specify the errorPlacement function.
<script>
$(document).ready(function(){
$(“#aspnetForm”).validate(
{
errorPlacement: function(error, element) {
error.insertBefore(element);
}
}
);
});
However in some situations this would mess up your design and therefore you might use a summary instead. To pinpoint a specific area where you’d like to have your summary displayed you can use an errorLabelContainer and even define if you’d like to wrap your elements with a specific tag.
<script>
$(document).ready(function(){
$(“#aspnetForm”).validate(
{
errorLabelContainer: “#ErrorBox”,
wrapper: “li”
}
);
});
/*
In your html you need to have your error box defined, since you reference it in your javascript
*/
<div><ul id=”ErrorBox”></ul></div>
You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
Looks like this will be helpful. Would you know if you can just place the error text right in the input box? Using labels for me breaks my layout. Suppose can hack the errorPlacement
Thank you for this post.
Yes you can do that. By providing your own placeholders in relation to the input, select, textarea element you can easily decide where the error output should go. The example below you can use as an example, and with some work you could probably find a space where it would not push your elements and destroy your layout.
E g.
$(document).ready(function () {
$(“#yourform”).validate(
{
errorPlacement: function (error, element) {
// find the parent div of the validated element and look for any child elements with class errorbox
var errorBox = element.parent(“div”).children(“.errorbox”);
// if element with class ‘errorBox’ is found- use it – else inject as normal
if (errorBox.length == 1)
error.appendTo(errorBox);
else
error.insertAfter(element);
}
});
});
I just want to extract the text message part and place in the input box. Im doing it this way in errorPlacement.
element.val(error.text())
Problem is if you click submit again with the error message in input box it might validate.
I have found that using this plugin is just to much trouble for what I want to do. I made a pure javascript solution in about an hour. If you know javascript and jquery you really dont need this plugin.
I think error message in the text box if big enough is the best way to go. It saves space and looks slick. Error messages on the side is so dated.
Nice Post