Share the ideas and thoughts, become united ...

Thursday, April 8, 2010

Rapid jQuery: HTML Form Validation

I have showed the idea of basic form validation with jQuery on my previous post. Now I am gonna show you guys how to speed up the validation process by using plug-in. Be ready to be amazed !

What we need :
  1. jQuery 
  2. jQuery Form Validation plug-in
  3. HTML codes :)
First we need to add the jQuery and the plug-in to our webpage which we want to validate.
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="jquery.validate.min.js"></script>
Now lets have a look at the form which has to be validated.

<form action="submit.php" method="post" id="doit" >
<fieldset>
    <label for="name">Name</label><br />
    <input type="text" id="name" name="name" class="required" minlength="2" /><br />
    <label for="email">Email</label><br />
    <input type="text" name="email" id="email" class="required email" /><br />
    <label for="zip_code">Zip code</label><br />
    <input type="text" name="digits" id="zip_code" class="required digits" /><br />
    <input class="submit" type="submit" value="Submit" />
</fieldset>
</form>
We have to set up some meta data in order to use the built in validation methods. We are using the label to notify the user about the field and also to display the error message. The important part is the for property. It is the same as the id of the component it is representing.
The next important part is the name property it must be one of the predefined class. some of the predefined classes are:
  • name - validation for common name
  • email - validation for email addresses
  • url - validation for url addresses
  • digits - validation for only digits
There are many predefined class. You can check the plug-in's documentation for complete list.
Next important property is class property. You can define your field to be required in the class property.
Note that the email input type has a class value of "required email". It means that the field is a necessary one and it must contain a valid email address.

Hope you have understand the basic behind the validation plug-in. Now we are only one step away from the validation process. Lets check it out -

<script type="text/javascript">
    $(document).ready(function () {
        $("#doit").validate();
    });
</script>
 Now we have to call the validate() method of the form. so we use the $("#doit") to select the whole form. And then call the validate() method to validate it.
Yes the validation is completed. Don't believe me? Why don't you just try it out.

Lastly you can add customization in the CSS section to change the way the message appears.
<style>
    label.error {
        color:#FF0000
    }
</style>
Here is a snapshot of the validation process :


Update - Here is the source code.
 If you have any suggestion or question, please let me know.

No comments:

Post a Comment