Guards is a plugin for jQuery that provides a simple, chainable, declarative API for guarding your forms against invalid user input. To get started, include the guards.js file after jQuery, and start declaring your guards. Note that you do not need to include this in a document.onready callback. All guarding happens via delegated events, which means the elements need not yet be defined. They can be defined later on, or even be added to the DOM after some user input.
Let's get started with an example. Go ahead and try to submit the form without any input. The inputs are guarded with the default guard, which is the "required" guard, which ensures something has been provided.
Now let's break down what is happening. The first line in the
script guards anything that matches
"form#form1 input[type='text']" selector
(which happens to be both text fields in the form). The second line
enables guards for the form, which hooks up events that prevent the
form from submitting if any of the guards fail to pass.
All guards automatically have delegated events hooked up (regardless
enableGuards is called for that form) which will
clear errors when the user starts to change that field.
Some built in guards
Customizing how guards work is pretty easy, but before we get into
deep customization, let's look at some of the built in guards. To
specify a built in guard, simply call the
with the name of the built in guard you would like to use. Try out
the following form with some of the built in guards.
Other ways of guarding the form
enableGuards function shown above is not the only
way to guard forms. There are two other ways of guarding forms.
There is the
enableGuards method on the jQuery object,
which will guard forms that have been selected via a jQuery
selector. This differs from the other function in that it will not
affect forms that are created at a later point. This means it must
be called after the document is ready, or at least after the form
has been declared.
The other method is
liveGuard, which takes a selector
and "live guards" any forms that match the selector. This uses
delegated events like the first
enableGuards, so it can
be done outside document.onready callbacks. A live guard is a guard
that will trigger errors as soon as the user changes a field. The
field will still trigger errors on submit, but user changes make it
easy for the user to realize mistakes as they happen. Note that for
text fields, the change won't trigger the error until the focus
leaves the field.
Try out the alternative methods below: