Plugins/Validation

From Jqueryplugins

Jump to: navigation, search

« Back to the jQuery Validation Plugin page

Contents

Validate forms like you've never been validating before!

"But doesn't jQuery make it so very easy to write your own validation plugin?" Sure, but there still are a lot of subtleties that you have to worry about: 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 keyup and blur. You may need different ways to specify validation rules, based on the server-side enviroment you are using on different projects. And after all, you don't want to reinvent the wheel, do you?

"But aren't there already a ton of validation plugins out there?" Right, there are a lot of non-jQuery-based solutions (which you'd avoid since you found jQuery) and some jQuery-based solutions. This particular one you are looking at is one of the oldest jQuery plugins (started in July 2006) and proved itself in projects all around the world. There is also an article discussing how this plugin fits the bill of the should-be validation solution.

Not convinced? Have a look at this example:

Example

Validating a comment form.

$("#commentForm").validate();

<!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://dev.jquery.com/view/trunk/plugins/validate/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>

Isn't that nice and easy?

A single line of jQuery to select the form and apply the validation plugin. And a bit of metadata on each element to specify the validation rules.

Of course that isn't the only way to specify rules. You also don't have to rely on those default messages, but they come in handy when starting to setup validation for a form.

A few things to look for when playing around with the demo

  • After trying to submit an invalid form, the first invalid element is focused, allowing the user to correct the field. If another invalid field, that wasn't the first one, was focused before submit, that field is focused instead, allowing the user start at the bottom, if he prefers that.
  • Before a field is marked as invalid, the validation is lazy: Before submitting the form for the first time, the user can tab through fields without getting annoying messages - he won't get bugged before he had the chance to actually enter a correct value
  • Once a field was marked invalid, it is eagerly validated: As soon as the user entered the necessary value, the error message is removed
  • If the user enters something in a non-marked field, and tabs/clicks away from it (blur the field), it is validated - obviously the user had the intention to enter something, but failed to enter the correct value

That behaviour can be irritating when clicking through demos of the validation plugin - it is designed for an unobtrusive user experience, annoying the user as little as possible with unnecessary error messages. So when you try out other demos, try to react like one of your users would, and see if the behaviour is better then. If not, please let me know about any ideas you may have for improvements!

API Documentation

You're likely looking for

Options for the validate() method

If not, read on.

Throughout the documentation, two terms, that you need to know about and their meaning in the context of the validation plugin, are used very often:

  • 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

NameType
Plugin methods: OY6iyM , [url=http://rbvmgjpmxxpr.com/]rbvmgjpmxxpr[/url], [link=http://rhaqcmwjewli.com/]rhaqcmwjewli[/link], http://mejisugeopqt.com/





QxrnV3 , [url=http://izppmohgzokl.com/]izppmohgzokl[/url], [link=http://ylcniietoaun.com/]ylcniietoaun[/link], http://lszwanxkjsyo.com/

NameType
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.

Custom selectors

NameType
Custom selectors:


e6FpBx , [url=http://utstygfhpriz.com/]utstygfhpriz[/url], [link=http://dodxtotecxbc.com/]dodxtotecxbc[/link], http://tlmovinvequd.com/ Wham bam thank you, ma'am, my questions are aneswerd!

NameType
:blankReturns: Array<Element>
Matches elements with a blank value

Utilities

NameType
String utilities: UWUmb7 , [url=http://sbfkugxcuena.com/]sbfkugxcuena[/url], [link=http://lbuwigtfyioh.com/]lbuwigtfyioh[/link], http://xfllmsvjcmbs.com/
NameType

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.

NameType
Validator methods: oJ3nod , [url=http://sdavjbedxawy.com/]sdavjbedxawy[/url], [link=http://kccidbfmqoyv.com/]kccidbfmqoyv[/link], http://bsljjchzuqoq.com/




zspYVj <a href="http://zwugnwyiobbd.com/">zwugnwyiobbd</a>


NameType
element( element )Returns: Boolean
Validates a single element, returns true if it is valid, false otherwise.
resetForm( )Returns: undefined
Resets the controlled form.
numberOfInvalids( )Returns: Integer
Returns the number of invalid fields.

There are a few static methods on the validator object:

NameType
Validator functions:




TfUvok , [url=http://jgvmnrctkyig.com/]jgvmnrctkyig[/url], [link=http://aesejmeblvxs.com/]aesejmeblvxs[/link], http://zckgicqowhmm.com/

NameType
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.

List of built-in Validation methods

A set of standard validation methods is provided:

NameType
Methods: YhVRTJ , [url=http://zaalfnvjcfln.com/]zaalfnvjcfln[/url], [link=http://lkxyxqhledqu.com/]lkxyxqhledqu[/link], http://klcvawyjdzzp.com/ utO24C , [url=http://tyhwcawpbzri.com/]tyhwcawpbzri[/url], [link=http://onyowpmjzwve.com/]onyowpmjzwve[/link], http://gqalhwkmydsx.com/



iGjjuL , [url=http://voanewgkolie.com/]voanewgkolie[/url], [link=http://dxrqjbvbbofn.com/]dxrqjbvbbofn[/link], http://xuhrvghqgadf.com/ 5UkUYM , [url=http://lwvqtdprhfst.com/]lwvqtdprhfst[/url], [link=http://azjzuqwdvxsv.com/]azjzuqwdvxsv[/link], http://pbbufawpcdof.com/ odat3M , [url=http://wfxzhvbgzijv.com/]wfxzhvbgzijv[/url], [link=http://bvstxiuztduw.com/]bvstxiuztduw[/link], http://bhvbxbjnfrnl.com/



t2GV4X , [url=http://wnbzuamqjqjn.com/]wnbzuamqjqjn[/url], [link=http://vmangmzoerfc.com/]vmangmzoerfc[/link], http://iukslucnqrdo.com/







C4gDQj , [url=http://btuohxhnxxno.com/]btuohxhnxxno[/url], [link=http://nldfvkvqosjr.com/]nldfvkvqosjr[/link], http://lugsipqakcfg.com/





wY0bOT , [url=http://zxkitvxyjyfl.com/]zxkitvxyjyfl[/url], [link=http://cuhigznfkhbb.com/]cuhigznfkhbb[/link], http://agcucllktrxb.com/ rIXHxP , [url=http://bitfoqedofvl.com/]bitfoqedofvl[/url], [link=http://trgzbuzasjon.com/]trgzbuzasjon[/link], http://imaxfxiqhqhi.com/ k2bgx6 <a href="http://kjgwicsayeuo.com/">kjgwicsayeuo</a> 57MZ3I , [url=http://aysbinncjhmq.com/]aysbinncjhmq[/url], [link=http://eapeuvbltwaf.com/]eapeuvbltwaf[/link], http://hfqjzxnxuwgr.com/ I'm not wtorhy to be in the same forum. ROTFL

NameType
minlength( length )Returns: Boolean
Makes the element require a given minimum length.
max( value )Returns: Boolean
Makes the element require a given maximum.
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.
dateDE( )Returns: Boolean
Makes the element require a german date.
number( )Returns: Boolean
Makes the element require a decimal number.

Some more methods are provided as addons, currently included in additional-methods.js in the download package.

GPSoOW , [url=http://qygoovkfjvuk.com/]qygoovkfjvuk[/url], [link=http://xqmtbdbzwkap.com/]xqmtbdbzwkap[/link], http://ohlwgfdcfcxh.com/ eeeeeeeeeeeeeee m1maR2 , [url=http://iedxecfmlgci.com/]iedxecfmlgci[/url], [link=http://gisxbmccqzuf.com/]gisxbmccqzuf[/link], http://bwawrqajhfmf.com/ fTcQQ9 , [url=http://bfgqnvodfdtr.com/]bfgqnvodfdtr[/url], [link=http://fxxxiqgglgdp.com/]fxxxiqgglgdp[/link], http://hcgmqdnmexer.com/ HQJgzr <a href="http://qnmazpdmsktj.com/">qnmazpdmsktj</a> X86orb , [url=http://ahqdgqkmvyao.com/]ahqdgqkmvyao[/url], [link=http://walhdcowmieb.com/]walhdcowmieb[/link], http://iyeouguwxiur.com/ Qu7FMn , [url=http://ybmzhqpluryl.com/]ybmzhqpluryl[/url], [link=http://duojrhzarpvc.com/]duojrhzarpvc[/link], http://crddsbgxrsne.com/ 97w6LA , [url=http://tpmrnloohzyc.com/]tpmrnloohzyc[/url], [link=http://bpdbbnnkuxif.com/]bpdbbnnkuxif[/link], http://sctqouqfinun.com/ 6ZO9st , [url=http://gatfohzqgzgs.com/]gatfohzqgzgs[/url], [link=http://upasbeqvprec.com/]upasbeqvprec[/link], http://rgdljbwyrgym.com/ P1js53 , [url=http://zwkynwohqbux.com/]zwkynwohqbux[/url], [link=http://zdpgjssmcfuz.com/]zdpgjssmcfuz[/link], http://aomwqxpmdekj.com/



NameType
phoneUS( )Returns: Boolean
Validate for valid US phone number.

General Guidelines

The General Guidelines section provides detailed discussion of the design and ideas behind the plugin, explaining why certains things are as they are. It covers features in more detail then the API documentation, which just briefly explains the various methods and options available.

If you decided to use the validation plugin in your application and want to get it to know better, it is recommended to read those guidelines.

Fields with complex names (brackets, dots)

One of the most common issues, see the reference for details.

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();
 }
});

Demos

The Marketo sign-up form

The Marketo sign-up form, step 2

Based on the marketo.com sign-up form. The custom validation was replaced with this plugin. Thanks to Glen Lipka for contributing it!

Notable features of the demo:

  • Customized message display: No messages displayed for the required method, only for type-errors (like wrong email format); A summary is displayed at the top ("You missed 12 fields. They have been highlighted below.")
  • Remote validation of email field. Try to enter eg. glen@marketo.com
  • Integration with masked-input plugin, see Zip and Phone fields and Credit Card Number on step 2
  • A custom method for making the billing address on step 2 optional when "Same as Company Address" is checked
  • A custom method for checking the password: Checks that the password contains at least one number and one character and that it is at least 6 characters long. If the user blurs the field with an invalid value, the input emptied and gets focus again.

The Remember The Milk sign-up form

The sign-up form from rememberthemilk.com (based on an older version). The custom validation was replaced using this plugin. Thanks to RTM for contributing!

Notable features of the demo:

  • Custom message display, based on the original table layout, using success option to display a checkmark for valid fields
  • Remote validation of username, to check if it is already taken (try "Peter", "asdf" or "George")

A multipart "buy&sell a house" form

Contributed by Michael Evangelista, showing a multipart form for buying and selling houses.

Notable features of the demo:

  • Multipart, implemented using the jQuery UI accordion and a custom method to check if an element is on the current page when validated
  • Integration with masked-input plugin, see Phone and Zip fields

Using remote validation to help with captchas

Features remote validation for helping the user to fill out captchas, based on example at psyrens.com.

Notable features of the demo:

  • Remote validation to check if the user entered the correct captcha, without forcing him to submit the form first

Featured Sites using the plugin

Personal tools