Sei sulla pagina 1di 7

jQueryPluginsUIM eetupsForumBlogAboutDonate

Download Documentation Tutorials Bug Tracker Discussion

DOCUMENTATION

Search jQuery

GETTING STARTED M ain Page Downloading jQuery How jQuery Works FAQ Tutorials Using jQuery with Other Libraries Variable Types

Plugins/Validation
From jQuery JavaScript Library
Back to the jQuery Validation Plugin page

API REFERENCE jQuery Core Selectors Attributes Traversing M anipulation CSS Events Effects Ajax Utilities jQuery UI

CONTENTS
1 Validate forms like you've never been validating before! 2 Example 2.1 Isn't that nice and easy? 2.2 A few things to look for when playing around with the demo 3 API Documentation 3.1 Options for the validate() method 3.2 Plugin methods 3.3 Custom selectors 3.4 Utilities

PLUGINS Plugin Repository Authoring

3.5 Validator 3.6 List of built-in Validation methods 4 General Guidelines

SUPPORT M ailing List and Chat Submit New Bug Commercial Support

4.1 Fields with complex names (brackets, dots) 4.2 Too much recursion 5 Demos 5.1 The Marketo sign-up form 5.1.1 The Marketo sign-up form, step 2 5.2 The Remember The Milk sign-up form 5.3 A multipart "buy&sell a house" form 5.4 Using remote validation to help with captchas 6 Featured Sites using the plugin

ABOUT JQUERY Contributors History of jQuery Sites Using jQuery Browser Compatibility Licensing Donate

TOOLBOX What links here Related changes Upload file Special pages Printable version Permanent link

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

VIEWS Article Discussion Edit History

PERSONAL TOOLS Log in / create account

EXAMPLE
Demo View Source Validating a comment form.
$"cmetom)vldt(; (#omnFr".aiae)

docs.jquery.com/Plugins/Validation

1/7

<DCYEHM PBI "/WC/T HM 40 Tastoa/E" !OTP TL ULC -/3/DD TL .1 rniinl/N "tp/www.r/Rhm4loedd> ht:/w.3ogT/tl/os.t" <tl hm> <ed ha> <citsc"tp/cd.qeycmjur-aetj"<srp> srp r=ht:/oejur.o/qeylts.s>/cit <tl tp=tx/s" sye ye"etcs> *{fn-aiy Vraa fn-ie 9% } otfml: edn; otsz: 6; lbl{wdh 1e;fot lf;} ae it: 0m la: et lblerr{fot nn;clr rd pdiglf:.e;vria-lg:tp } ae.ro la: oe oo: e; adn-et 5m etclain o; p{cer bt;} la: oh .umt{mri-et 1e;} sbi agnlf: 2m e {fn-egt bl;pdigrgt 1m vria-lg:tp } m otwih: od adn-ih: e; etclain o; <sye /tl> <cit srp> $dcmn)rayfnto({ (ouet.ed(ucin) $"cmetom)vldt(; (#omnFr".aiae) }; ) <srp> /cit <ha> /ed <oy bd>

<cittp=tx/aacit sc"tp/jafee.ihbcmjur-aiainjur.aiaej"<srp srp ye"etjvsrp" r=ht:/zefrrgtu.o/qeyvldto/qeyvldt.s>/ci

<omcas"mfr"i=cmetom mto=gt ato=" fr ls=cxom d"omnFr" ehd"e" cin"> <ilst fede> <eedAsml cmetfr wt sbi vldto addfutmsae<lgn> lgn> ipe omn om ih umt aiain n eal esgs/eed <> p <ae fr"nm"Nm<lbl lbl o=cae>ae/ae> <m*/m<nu i=cae nm=nm"sz=2"cas"eurd mnegh""/ e><e>ipt d"nm" ae"ae ie"5 ls=rqie" ilnt=2 > <p /> <> p <ae fr"eal>-al/ae> lbl o=cmi"EMi<lbl <m*/m<nu i=cmi"nm=eal sz=2" cas"eurdeal / e><e>ipt d"eal ae"mi" ie"5 ls=rqie mi" > <p /> <> p <ae fr"ul>R<lbl lbl o=cr"UL/ae> <m e> <e>ipti=cr"nm=ul sz=2" cas"r"vle" / /m<nu d"ul ae"r" ie"5 ls=ul au=" > <p /> <> p <ae fr"cmet>orcmet/ae> lbl o=comn"Yu omn<lbl <m*/m<etrai=comn"nm=cmet cl=2" cas"eurd>/etra e><e>txae d"cmet ae"omn" os"2 ls=rqie"<txae> <p /> <> p <nu cas"umt tp=sbi"vle"umt/ ipt ls=sbi" ye"umt au=Sbi"> <p /> <fede> /ilst <fr> /om <bd> /oy <hm> /tl

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.

docs.jquery.com/Plugins/Validation

2/7

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:

Name validate( options ) Validates the selected form. valid( ) rules( ) Return the validations rules for the first selected element. rules( "add", rules ) Returns: Options

Type Returns: Validator Returns: Boolean Returns: Options

Checks whether the selected form is valid or whether all selected elements are valid.

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:

Name :blank :filled :unchecked

Type Returns: Array<Element> Returns: Array<Element> Returns: Array<Element>

Matches elements with a blank value Matches elements with a value. Matches all elements that are unchecked.

Utilities
NameType

String utilities:

Name jQuery.validator.format( template, argument, argumentN... ) Replaces {n} placeholders with arguments.

Type Returns: String

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.

docs.jquery.com/Plugins/Validation

3/7

NameType

Validator methods:

Name form( ) element( element ) resetForm( ) Resets the controlled form. showErrors( errors ) Show the specified messages. numberOfInvalids( ) Returns the number of invalid fields.

Type Returns: Boolean Returns: Boolean Returns: undefined Returns: undefined Returns: Integer

Validates the form, returns true if it is valid, false otherwise. Validates a single element, returns true if it is valid, false otherwise.

There are a few static methods on the validator object: NameType

Validator functions:

Name setDefaults( defaults ) Modify default settings for validation. addMethod( name, method, message )

Type Returns: undefined 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 ) addClassRules( rules ) Returns: undefined Returns: undefined Add a compound class method - useful to refactor common combinations of rules into a single class. 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:

docs.jquery.com/Plugins/Validation

4/7

Name required( ) Makes the element always required. required( dependency-expression ) required( dependency-callback ) remote( options ) minlength( length ) Makes the element require a given minimum length. maxlength( length ) rangelength( range ) Makes the element require a given value range. min( value ) Makes the element require a given minimum. max( value ) Makes the element require a given maximum. range( range ) Makes the element require a given value range. email( ) Makes the element require a valid email url( ) Makes the element require a valid url date( ) Makes the element require a date. dateISO( )

Type Returns: Boolean Returns: Boolean Returns: Boolean Returns: Boolean Returns: Boolean Returns: Boolean Returns: Boolean Returns: Boolean Returns: Boolean Returns: Boolean Returns: Boolean Returns: Boolean Returns: Boolean Returns: Boolean

Makes the element required, depending on the result of the given expression. Makes the element required, depending on the result of the given callback. Requests a resource to check the element for validity.

Makes the element require a given maxmimum length.

docs.jquery.com/Plugins/Validation

5/7

Makes the element require a ISO date. number( ) Makes the element require a decimal number. digits( ) Makes the element require digits only. creditcard( ) Makes the element require a creditcard number. accept( extension ) Makes the element require a certain file extension. equalTo( other ) 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. Returns: Boolean Returns: Boolean Returns: Boolean Returns: Boolean Returns: Boolean

Plugins/Validation/CustomMethods/minWordsPlugins/Validation/CustomMethods/maxWordsPlugins/Validation/CustomMethods/rang

Plugins/Validation/CustomMethods/nowhitespace Plugins/Validation/CustomMethods/ziprange Plugins/Validation/CustomMethods/vinUS Plugins/Validation/CustomMethods/dateITA

Name phoneUS( )

Type 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:
$"mfr".aiae{ (#yom)vldt( sbiHnlr fnto(om { umtade: ucinfr) / sm ohrcd / oe te oe / myedsbigsbi bto / ab ialn umt utn / te: / hn $fr)sbi(; (om.umt) } }; )

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:
$"mfr".aiae{ (#yom)vldt( sbiHnlr fnto(om { umtade: ucinfr) fr.umt) omsbi(; } }; )

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

docs.jquery.com/Plugins/Validation

6/7

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


newsweek.com for the registration soundcloud.com cloud music sharing Retrieved from "http://docs.jquery.com/Plugins/Validation"

2010 The jQuery Project


Sponsored by Media Temple and others.

Download Documentation Tutorials Bug Tracker Discussion

docs.jquery.com/Plugins/Validation

7/7

Potrebbero piacerti anche