h5Validate - HTML5 Form Validation for jQuery

Download from Github

By Eric Elliot, author: "Programming JavaScript Applications" (O'Reilly)

Need to brush up? See "Learning JavaScript: Up to Speed in No Time"

If you want to contribute, feel free to fork the project on Github.

Best practice realtime HTML5 form validation for jQuery. Works on all popular browsers, including old ones like IE6.

Supported Platforms

Desktop: IE 9, 8, 7, 6, Chrome, Firefox, Safari, and Opera. Tested on Windows 7 and Mac.

Mobile: iPhone, Android, Palm WebOS

New in v0.8.0+

Jump Start

Copy and paste this at the end of the body on any page with an HTML5 form. If html5 validation rules exist in the form, you're in business!

Features

HTML5 required attribute. e.g.

Hint: Select it, then click somewhere else without typing anything.

Source:

HTMTL5 pattern attribute. e.g.

Hint: It's expecting mm/dd/yyyy. Try typing "jQuery rocks!" instead.

Source:

Pattern Library

Sometimes, you'll want to re-use the same validation pattern for several elements on a page. You could copy and paste the same pattern over and over again to a bunch of different form fields, but what happens if you discover a bug in the pattern? Fix it and repeat the whole copy and paste process?

A better solution is to attach the pattern with a class selector. Use $.h5Validate.addPatterns() to add your pattern, make sure the classPrefix variable is set correctly (it's h5- by default), and add the class to the input fields.

Source:

Error Messages

Error divs should be hidden in the HTML with display:none; -- h5Validate shows them when the corresponding field is marked invalid.

Options

There are a ton of options you can override by passing key: value pairs when you call .h5Validate(). For example, we can change the CSS class that indicates validation errors:

Hint: Select it, then click somewhere else without typing anything.

Source:

errorClass

Custom CSS class for validation errors.

validClass

Custom CSS class to mark a field validated.

errorAttribute

An html attribute that stores the ID of the error message container for this element. It's set to data-h5-errorid by default. Note: The data- attribute prefix is a new feature of HTML5, used to store an element's meta-data. e.g.

<input id="name" data-h5-errorid="nameError" required >
kbSelectors

A list of CSS selectors for attaching keyboard-oriented events. Default:

kbSelectors: ':text, :password, select, textarea'
focusout, focusin, change, keyup

(Events) These are the "keyboard oriented" events. Better to think of them as non-mouse-specific events. Set them to "true" if you want them to trigger a field validation. Defaults:

focusout: true,
focusin: false,
change: false,
keyup: true
mSelectors

A list of CSS selectors for attaching "mouse oriented" events. Default:

mSelectors: ':radio, :checkbox, select, option'
click

(Event) The only default mouse-oriented event. Since it probably makes little sense to trigger validation on other mouse events, I'll leave it to you to figure out how to enable them.

Note: The click event isn't just for the mouse. It will trigger for keyboard and touch screen interactions, too.

click: true

Event API

h5Validate supports the following events:

instance
Instance created.
validated
The element in question has been validated. A validity object is passed into the event handler containing:
{
	element: HTMLObject, // A reference to the validated element
	customError: Bool, // Custom validity failed.
	patternMismatch: Bool, // Input does not match pattern
	rangeOverflow: Bool, // Input is greater than max attribute value
	rangeUnderflow: Bool, // Input is less than min attribute value
	stepMismatch: Bool, // Input does not conform to the step attribute setting
	tooLong: Bool, // Input is too long
	typeMismatch: Bool, // Wrong input type
	valid: Bool, // Input is valid
	valueMissing: Bool // Required value is missing
}
formValidated
The form in question has been validated. An object is passed with an object containing a bool, valid, and an array of validity objects corresponding to the validated elements.

Methods

$.h5Validate.addPatterns(patterns)

Take a map of pattern names and HTML5-compatible regular expressions, and add them to the patternLibrary. Patterns in the library are automatically assigned to HTML element pattern attributes for validation.

{object} patterns

A map of pattern names and HTML5 compatible regular expressions.

Demo

Source:

The class="h5-phone" bit is the part doing the magic. The h5- prefix tells you that this class is a handle that we can use to attach validation rules to. Internally, we just tack this prefix to the front of the pattern names to get the right selectors.

In your JavaScript, specify the pattern name without the class prefix. Keeping the prefix off lets us easily share and re-use pattern libraries between projects.


$.h5Validate.validValues(selector, values)

Take a valid jQuery selector, and a list of valid values to validate against.

If the user input isn't in the list, validation fails.

{String} selector

Any valid jQuery selector.

{Array} values

A list of valid values to validate selected fields against.

New Input Types (Use with caution.)

Warning: Each browser has its own way of treating these new input types. iOS might swap out the on-screen keyboard (cool!), while Chrome renders custom UI controls that don't always make sense (like up and down arrows for datetime inputs.)

What's worse, some of the styles that get applied to these elements are browser-specific, and ignore CSS cascading -- so before you can add your own look and feel, you first have to turn off each native browser's look and feel. For example, h5Validate works just fine on that search field down there, but in Chrome, it ignores our CSS because you first have to turn off -webkit-appearance: searchfield; before you style it. (Hint: You may want to search for a good HTML5 CSS reset). I've left it as is to demonstrate how irritating all of this can be. Good luck, and don't say I didn't warn you.

h5Validate does not currently validate new element types automatically. The pattern and required attributes work fine, but h5Validate will not automatically apply email validation to fields with type="email", etc.. (Yet.)

The plan is to create a thorough testsuite to make sure these validations comply with the html5 standard prior to implementation. So far, it looks like some of the browser implementations are inconsistent. We'll be sharing test cases and filing bug reports in an effort to get all of these validations behaving the same way. Any help with the effort is appreciated. In particular, test cases that show how various implementations differ from the spec would be great. Eventually, we'll defer to the native browser implementation if it's available, with a fall-back to h5Validate's built-in validation rules.

For you bleeding-edge junkies, here are the new input types:

Run Tests

QUnit Test Suite