Form Verification Example
We’ll close our discussion of
forms with an extended example that demonstrates several of the
concepts we’ve been discussing. Example 15-2
shows how you might use the onsubmit
event handler
of the Form object to perform input validation so that you can notify
the user and prevent the form from being submitted when it contains
missing or invalid data. After studying this example, you may want to
turn back to Example 1-3, the form-programming
example we began this book with. The code of that example probably
makes more sense now that you are a JavaScript expert!
Example 15-2 defines a verify( )
function suitable for use as a generic
form validator. It checks for required fields that are empty. In
addition, it can check that a numeric value is in fact numeric and
also falls within a specified numeric range. This verify( )
function relies on the type
property
of a form element to determine which kind of element it is. The
function also relies on additional user-defined properties to
distinguish optional fields from required fields and to specify the
allowed ranges for numeric fields. Note how the function reads the
value
property of an input field and uses the
name
property of a field when reporting errors.
Figure 15-2 shows an example form that uses this verification scheme, with the error message that is displayed when the user attempts to submit the form before correctly filling it in.
Figure 15-2. A form that failed validation
Example 15-2. Performing ...
Get JavaScript: The Definitive Guide, Fourth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.