jQuery: The Write Less, Do More JavaScript Library

Plugins/Validation

From jQuery JavaScript Library

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>
  <link rel="stylesheet" href="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.css" type="text/css" media="screen" />
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/lib/jquery.delegate.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 sumitting an invalid form, the first invalid element is focused, allowing the user to correct the field. If another field 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 improvments!

API Documentation

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: Boolean
Return the validations rules for the first selected element.

Custom selectors

NameType
Custom selectors:




NameType
:blank Returns: Array<Element>
Matches elements with a blank value
:filled Returns: Array<Element>
Matches elements with a value.
:unchecked Returns: Array<Element>
Matches all elements that are unchecked.

Utilities

NameType
String utilities:


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

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

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( url ) 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

Goals

The ultimate goal of this plugin is to make working with forms more fun for anyone. By improving the interaction, it is easier and less annoying for the user to fill out the form and submit it.

To achieve that goal, it is important that the plugin is actually deployed on websites around the world, so a lot of focus is spent on making it easy for a developer, you, to use the plugin.

Markup recommendations

Each input has a label associated with it: The for-attribute of the label refers to the id-attribute of the input.

  <label for="firstname">Firstname</label><input id="firstname" name="fname" />

Methods

A validation method implements the logic to validate any element. Provided are a set of default validation methods, like required. Except required itself and equalTo, all validation methods declare an element valid when it has no value at all. That way an email field is optional, unless also required is specified. you can specify an element input to contain a valid email address, or nothing at all. Use $.validator.addMethod to implement custom methods.

Rules

A validation rule applies one or more validation methods to an input element. You can specify validation rules via metadata or via plugin settings (option rules). The decision is often influenced by serverside infrastructure. If a web framework is used, its often easier to use metadata, which is also good for fast prototyping. Plugin settings produce cleaner markup, though valid markup results from both.

Fields with complex names (brackets, dots)

If your form consists of fields using names that aren't legal JavaScript identifiers, you have to quote those names when using the rules option:

$("#myform").validate({
  rules: {
    // no quoting necessary
    name: "required",
    // quoting necessary!
    "user[email]": "email",
    // dots need quoting, too!
    "user.address.street": "required"
  }
});

Error messages

An error message displays a hint for the user about invalid elements, and what is wrong. There are three ways to provide error messages. Via the title attribute of the input element to validate, via error labels and via plugin settings (option messages).

All included validation rules provide a default error message which you can use for prototyping, because it is used when no specific message is provided.

The priorities are as follows: A custom message (passed by plugin options), the element's title, the default message.

Error messages and Google Toolbar conflicts

Google Toolbar's AutoFill feature sometimes conflicts with the validation plugin's message display. Google Toolbar replaces the title attribute of an element with some hint at it's AutoFill. The validation plugin then uses that title attribute to display it as an error message - not the intended behaviour. One workaround to avoid that is to clear affected elements on DOM load:

 $("input.remove_title").attr("title", "");

More details in this article.

Error message display

Error messages are handled via label elements with an additional class (option errorClass). The link between the message and the invalid element is provided via the label's for attribute. When provided in the markup, they are shown and hidden accordingly, otherwise created on demand. By default, labels are created after the invalid element, this is also customizable (option errorPlacement). It is also possible to put them into an error container (option errorLabelContainer). To use a different element then a label, specify the errorElement option.

General messages

In addition to field-specific messages you can display a general "your form is invalid, please fix the highlighted fields!" message in a container anywhere on your page, eg. above the form (option errorContainer). The container is shown and hidden when errors occur and are fixed accordingly. The container for error labels (option errorLabelContainer) can also be nested inside the error container.

Focusing of invalid elements

By default, the first invalid element in a form is focused after submitting a form with invalid elements. To prevent confusion on the behalf of the user, the plugin remembers the element that had focus when the form was submitted, and refocuses that element. That way the user can try to fill out elements of the form at the end, without being forced to focus them again and again. This can be disabled (option focusInvalid).

Form submit

By default, the form submission is prevented when the form is invalid, and submitted as normal when it is valid. You can also handle the submission manually (option submitHandler).

Validation event

By default, forms are validated on submit, triggered by the user clicking the submit button or pressing enter when a form input is focused (option onsubmit). In addition, once a field was highlighted as being invalid, it is validated whenever the user types something in the field (option onkeyup). When the user enters something invalid into a valid field, it is also validated when the field loses focus (option onblur).

The goal of these interactions is to provide feedback as early as possible, while annoying the users as least as possible. Displaying error messages before the user had the chance to even type something is not helpful.


Validating multiple forms on one page

The plugin can handle only one form per call. In case you have multiple forms on a single page which you want to validate, you can avoid having to duplicate the plugin settings by modifying the defaults. Use $.validator.setDefaults({...}) to override multiple settings at once.

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