Documentation

Plugins/Validation

From jQuery JavaScript Library

(Redirected from Plugins/Validation/)
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 then 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 submitting 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:









NameType
validate( options )Returns: Validator
Validates the selected form.
valid( )Returns: Boolean
Checks if the selected form is valid or if 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

NameType
Custom selectors:




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

Utilities

NameType
String utilities:


NameType
jQuery.validator.format( template, argumentargumentN... )Returns: String
Replaces {n} placeholders with arguments.

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:










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

NameType
Validator functions:








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

NameType
Methods:









































NameType
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.
dateDE( )Returns: Boolean
Makes the element require a german date.
number( )Returns: Boolean
Makes the element require a decimal number.
numberDE( )Returns: Boolean
Makes the element require a decimal number with german format.
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

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

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

Sites using the plugin