Form validation is the process of making sure the user of an HTML form
has entered legal values -- for example; legitimate state names and
valid postal codes -- into form fields. It's a good idea to do form
validation in client-side JavaScript because it saves a bit of network
traffic and therefore a bit of time. When a client-side validation
program determines that there's a problem, it can have the user fix it
before submission to the server. A server-side validation routine would
have to send an error message back to the client, where the user would
have to resubmit the form -- too much back-and-forth! The client side is
the place to do validation, and Bailey's approach is an easy way to
implement it.
Bailey's program -- called fValidate and encapsulated in a couple of .js
files that you can refer to with SRC attributes -- relies on the ALT
attribute of HTML form elements to specify what sort of validation is
required. When the form is submitted, the validation library intercepts
it, loops through all the elements of the form, and validates each one
based on the contents of its ALT attribute, if any. For example, you
might encode an INPUT element of type TEXT (a one-line text box) this
way:
<INPUT type="TEXT" size=11 name="zipCode" alt="zip" />
That tells the validation library to make sure that the field contains a
valid Zone Improvement Plan (ZIP) code -- a United States postal code.
The library includes code that defines ZIP codes (rather liberally) as
five-digit numbers, nine-digit numbers, a sequence of five digits
followed by a hyphen and a sequence of four numbers, or a sequence of
five digits followed by a space and a sequence of four numbers.
Other validation directives you can place in the ALT attribute include
one that catches letter and number strings of a required length, one
that checks for proper formatting of money values, and one that rejects
blank entries.
The beauty of the library is that it loops through the form elements
independent of their NAME attributes. Unless you require a change in the
validation rules -- for non-US postal codes, for example -- you
shouldn't have to alter anything in the library at all. Bailey's
fValidate is a very useful tool.