About Me

My photo
Ernakulam, Kerala, India
I am Sajadh, author of this blog. I run this with loads of passion.
If you are into java, you may find lot of interesting things around ...
Advance thanks for your queries to sajadhaja90@gmail.com.

Wednesday, 21 November 2012

JQuery Validate Plugin

Validating forms

You need a standard library of validation methods (think of emails, URLs, credit card numbers). You need to place error messages in the DOM and show and hide them when appropriate. You want to react to more than just a submit event, like key up and blur. You may need different ways to specify validation rules, based on the server-side enviroment you are using on different projects.

Example 

 Source Code:-

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<style type="text/css">
* { font-family: Verdana; font-size: 96%; }
label { width: 10em; float: left; }
label.error { float: none; color: red; padding-left: .5em; vertical-align: top; }
p { clear: both; }
.submit { margin-left: 12em; }
em { font-weight: bold; padding-right: 1em; vertical-align: top; }
</style>
  <script>
  $(document).ready(function(){
    $("#commentForm").validate();
  });
  </script>
 
</head>
<body>

 <form class="cmxform" id="commentForm" method="get" action="">
 <fieldset>
   <legend>A simple comment form with submit validation and default messages</legend>
   <p>
 <label for="cname">Name</label>

 <em>*</em><input id="cname" name="name" size="25" class="required" minlength="2" />
   </p>
   <p>
  <label for="cemail">E-Mail</label>
  <em>*</em><input id="cemail" name="email" size="25"  class="required email" />
  </p>
  <p>
   <label for="curl">URL</label>
   <em>  </em><input id="curl" name="url" size="25"  class="url" value="" />
  </p>
   <p>
   <label for="ccomment">Your comment</label>
   <em>*</em><textarea id="ccomment" name="comment" cols="22"  class="required"></textarea>
   </p>
   <p>
     <input class="submit" type="submit" value="Submit"/>
   </p>
 </fieldset>
 </form>
</body>
</html>

Validating a comment form.
$("#commentForm").validate();

Options for the validate() method

  • method: A validation method implements the logic to validate an element, like an email method that checks for the right format of an text input's value. A set of standard methods is available, and it is easy to write your own.
  • rule: A validation rule associates an element with a validation method, like "validate input with name "primary-mail" with methods "required" and "email".
For a start, the validate-method:

Plugin methods

Plugin methods:
validate( options )Returns: Validator
Validates the selected form.
valid( )Returns: Boolean
Checks whether the selected form is valid or whether all selected elements are valid.
rules( )Returns: Options
Return the validations rules for the first selected element.
rules( "add", rules )Returns: Options
Adds the specified rules and returns all rules for the first matched element. Requires that the parent form is validated, that is, $("form").validate() is called first.
rules( "remove", rules )Returns: Options
Removes the specified rules and returns all rules for the first matched element.
removeAttrs( attributes )Returns: Options
Remove the specified attributes from the first matched element and return them.

Custom selectors

Custom selectors:
:blankReturns: Array<Element>
Matches elements with a blank value
:filledReturns: Array<Element>
Matches elements with a value.
:uncheckedReturns: Array<Element>
Matches all elements that are unchecked.


Validator

The validate method returns a Validator object that has a few public methods that you can use trigger validation programmatically or change the contents of the form. The validator object has more methods, but only those documented here are intended for usage.
Validator methods:
form( )Returns: Boolean
Validates the form, returns true if it is valid, false otherwise.
element( element )Returns: Boolean
Validates a single element, returns true if it is valid, false otherwise.
resetForm( )Returns: undefined
Resets the controlled form.
showErrors( errors )Returns: undefined
Show the specified messages.
numberOfInvalids( )Returns: Integer
Returns the number of invalid fields.
There are a few static methods on the validator object:
Validator functions:
setDefaults( defaults )Returns: undefined
Modify default settings for validation.
addMethod( name, method, message )Returns: undefined
Add a custom validation method. It must consist of a name (must be a legal javascript identifier), a javascript based function and a default string message.
addClassRules( name, rules )Returns: undefined
Add a compound class method - useful to refactor common combinations of rules into a single class.
addClassRules( rules )Returns: undefined
Add compound class methods - useful to refactor common combinations of rules.

List of built-in Validation methods

A set of standard validation methods is provided:
Methods:
required( )Returns: Boolean
Makes the element always required.
required( dependency-expression )Returns: Boolean
Makes the element required, depending on the result of the given expression.
required( dependency-callback )Returns: Boolean
Makes the element required, depending on the result of the given callback.
remote( options )Returns: Boolean
Requests a resource to check the element for validity.
minlength( length )Returns: Boolean
Makes the element require a given minimum length.
maxlength( length )Returns: Boolean
Makes the element require a given maxmimum length.
rangelength( range )Returns: Boolean
Makes the element require a given value range.
min( value )Returns: Boolean
Makes the element require a given minimum.
max( value )Returns: Boolean
Makes the element require a given maximum.
range( range )Returns: Boolean
Makes the element require a given value range.
email( )Returns: Boolean
Makes the element require a valid email
url( )Returns: Boolean
Makes the element require a valid url
date( )Returns: Boolean
Makes the element require a date.
dateISO( )Returns: Boolean
Makes the element require a ISO date.
number( )Returns: Boolean
Makes the element require a decimal number.
digits( )Returns: Boolean
Makes the element require digits only.
creditcard( )Returns: Boolean
Makes the element require a creditcard number.
accept( extension )Returns: Boolean
Makes the element require a certain file extension.
equalTo( other )Returns: Boolean
Requires the element to be the same as another one



Warning:-

Too much recursion

Another common problem occurs with this code:
$("#myform").validate({
 submitHandler: function(form) {
   // some other code
   // maybe disabling submit button
   // then:
   $(form).submit();
 }
});
This results in a too-much-recursion error: $(form).submit() triggers another round of validation, resulting in another call to submitHandler, and voila, recursion. Replace that with form.submit(), which triggers the native submit event instead and not the validation.
So the correct code looks slightly different:

$("#myform").validate({
 submitHandler: function(form) {
   form.submit();
 }
});

No comments:

Post a Comment

You can enter queries here...