Chapter 14: Form Handling


One of the most common uses of JavaScript is for checking the contents of forms before sending them to server-side programs. Commonly known as form validation , this use of JavaScript was actually one of the original driving forces behind the development of the language and, as a result, most of the techniques presented in this chapter will work in even the oldest JavaScript implementations . However, while relatively straightforward to implement, JavaScript form validation is not always used properly, and many details, particularly those related to usability, are often brushed aside, so we ll present correct usage of form checking as well as the appropriate JavaScript syntax.

The Need for JavaScript Form Checking

It can be quite annoying to fill out a form on a Web site only to have the page returned with complaints about malformed data after a round-trip to the server. With JavaScript, we can cut down on the frustration of waiting for failure and improve the usability of Web forms by checking the data before it is submitted to the server for processing.

There are two primary approaches we can take to validate form entries using JavaScript. The first involves checking each field as it is filled in. The second approach is to check all the fields of a form when a submission is triggered. Finally, we can improve upon validation by creating a field-mask to keep bad data from even being entered in the first place.

While it would appear that JavaScript-based form validation is primarily a usability convenience, Web servers also benefit from form validation. Because incomplete or invalid form field entries can be caught before submission, the number of interactions the browser will make with the server decreases. This presumably leaves the server free to carry out other work in a more timely fashion, without getting bogged down responding to the majority of common mistakes.

To start our discussion, let s take a look at how to access the << form >> tag using JavaScript.




JavaScript 2.0
JavaScript: The Complete Reference, Second Edition
ISBN: 0072253576
EAN: 2147483647
Year: 2004
Pages: 209

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net