Sunteți pe pagina 1din 4


This article discusses client-side validation using jQuery's validation plugin. This

jQuery plugin has a

bunch of standard validation methods such as a required field, valid email
or URL, minimum and maximum lengths for a field, etc. In addition to
that you can customize the look and feel of the error messages and their
Library required

jQuery Library.

jQuery Validation Plugin.

Or alternatively you can use the hotlink welcome file:

//hosted by Microsoft Ajax CDN

//hosted by Google API



<title>Basic jQuery Validation</title>
<form id="myForm" name="" action="">
<label for="name">Name:&nbsp;</label> <input name="name"
size="20" />
<input class="submit" type="submit" value="Submit" />

Step 3: JS file (Simple validation rules)

$(function() {
rules : {
name : {
required : true,
messages : {
name : {
required : "Please enter a name",

Step 4: jQuery Validation CSS

Note: the jQuery Validation Plugin adds class error to the inputs/labels. You only style them!

#form label.error {

#form input.error {
border:1px solid red;

Lets add a bunch of new criteria such as minimum/maximum length and even
custom messages.

Ive also introduced the format method in the message. This lets us replace the
argument given for minlength and maxlength. Here we dont have to worry about
hard-coding that value if they ever change.

Writing Your Own Validation Method

In some cases if I can't find a suitable built-in method for my situation. Then I Can write my own
validation method

This is a regex example to test for special characters. Here Im allowing some
special characters but others Im not. So if you enter * or ! for example, you
will get the message. Pretty cool huh?
These are the steps I went through to understand this plugin. Im certainly not an
expert (far from it) so comments are most welcome. I hope this can help you on
your way.

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 thevalidate() function at
The two parameters we used are:

rules: allows you to specify which fields you want to validate. In this case, we are
validating name, email,url and 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".

You can find an exhaustive list of built-in validation methods