What we need :
- jQuery
- jQuery Form Validation plug-in
- HTML codes :)
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>Now lets have a look at the form which has to be validated.
<script type="text/javascript" src="jquery.validate.min.js"></script>
<form action="submit.php" method="post" id="doit" >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.
<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>
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
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 -
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.
<script type="text/javascript">
$(document).ready(function () {
$("#doit").validate();
});
</script>
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>Here is a snapshot of the validation process :
label.error {
color:#FF0000
}
</style>
Update - Here is the source code.
If you have any suggestion or question, please let me know.
No comments:
Post a Comment