A Simple Form
Let us start with a simple example. Our demonstration form contains four fields: name, e-mail, comment and URL. As you can see, the first three fields are required, whereas the URL field is optional. If you submit the form without filling in the required fields, you will be prompted with an error message.
Here is the code we used for the form in the demonstration above.
The code is quite straightforward and doesn't need much explanation. However, there are a few important points that I would like to bring to your attention.
- Remember to include the the jQuery library and the bassistance validation plugin. The link to the jQuery library must come first in the
headsection, otherwise the validation will not work.
- Remember to assign the
idattribute of the form and the
nameattribute of all the fields that you want to validate.
Now, let us see the
validate() function in detail.
All we are doing here is initializing the validation of the form using the
validate() function. It can take several parameters. In the example above, we use only two of them, but you can find a list of all the options for the
validate() function at http://docs.jquery.com/Plugins/Validation/validate#toptions.
The two parameters we used are:
rules: allows you to specify which fields you want to validate. In this case, we are validating
comment. For each field, we specify if the field is required (
required: true). We can specify that it must be a valid e-mail address, URL, etc.
messages: allows you to specify the error message for a particular field (like the comments field in the example above). If you don't specify it, a default message is provided that says "this field is required".
In the example above, we only used three validation methods (
url). There are several other methods that can be used here. Here are a few of them:
remote: requests a resource to check the element for validity.
min: makes the element require a given minimum.
date: makes the element require a date.
creditcard: makes the element require a credit card number.
equalTo: requires the element to be the same as another one.
You can find an exhaustive list of built-in validation methods at http://docs.jquery.com/Plugins/Validation.
"But I can't find a suitable built-in method for my situation. Can I write my own method?" Yes you can! And its really easy.
Writing Your Own Validation Method
Consider a form where the user chooses his favorite sport. If he submits the form without choosing a sport, he is prompted with an error message.
As there is no built-in method to validate a drop down menu, we need to define our own method.
We do so by calling the
jQuery.validator.addMethod() method. It takes three parameters:
method: the actual method implementation, returning true if an element is valid.
message: The default message to display for this method.
In the validate function, we specify that the 'sport' field should be validated using the
Original: February 26, 2009