Skip to Content
JavaScript: The Definitive Guide, Fourth Edition
book

JavaScript: The Definitive Guide, Fourth Edition

by David Flanagan
November 2001
Intermediate to advanced
936 pages
68h 43m
English
O'Reilly Media, Inc.
Content preview from JavaScript: The Definitive Guide, Fourth Edition

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

JavaScript: A Beginner's Guide, Fourth Edition, 4th Edition

JavaScript: A Beginner's Guide, Fourth Edition, 4th Edition

John Pollock
JavaScript Cookbook, 3rd Edition

JavaScript Cookbook, 3rd Edition

Adam D. Scott, Matthew MacDonald, Shelley Powers

Publisher Resources

ISBN: 0596000480Supplemental ContentCatalog PageErrata