ptg16476052
528 LESSON 19: Using JavaScript in Your Pages
Validating Forms with JavaScript
Remember the sample form that you created back in Lesson 12, “Designing Forms”? It’s
shown again in Figure 19.1. It’s a typical registration form for a website, with several
required f ields.
What happens when this form is submitted? In the real world, a script on the server side
validates the data that the visitor entered, stores it in a database, and then thanks the visi-
tor for her time.
But what happens if a visitor doesn’t fill out the form correctly—for example, she doesn’t
enter her name or choose a value for gender? The script can check all that informa-
tion and return an error. The good thing about server-side validation is that it’s reliable.
The web developer can be completely certain that the user’s input has been validated
before the script tries to store it in the database. However, validating the form input in
the browser before it’s submitted has some advantages as well. The validation can be
designed to occur when it makes the most sense for the form in question, as opposed to
waiting for the user to click the Submit button. Furthermore, saving round trips to the
server conserves resources and offers better performance for users.
FIGURE 19.1
The registration
form.