Validating User Input
You should never trust your users, at least not when it comes to entering information in the format you need. Often, you need to make sure the input is valid before you continue to process a request. A date, for instance, can be written in many different formats. If you’ve traveled to the United States, and you’re not a U.S. citizen, you probably have had to fill out both an I-94 and a customs declaration form to be admitted by an immigration officer. You may have noticed that on one of the forms you need to write your birth date as yy/mm/dd and on the other as mm/dd/yy. I always get it wrong.
The entry form used in the examples in this chapter has a number of
fields that must be validated: a name must be entered, the birth date
must be a valid date, the email address must at least look like a
real mail address (it’s basically impossible to
verify that it is in fact real), the gender must be one of
m (male) or
f (female), the
lucky number must be a number between 1 and 100, and if any food
favorites are selected, each must be one of
p (pasta) or
Simple input can be validated using the standard JSTL actions, but for more complex validation rules, a bean is a good choice. We will look at both approaches next. If you use JSP combined with servlets, the input validation is typically done by the servlet and the JSP pages are invoked only if the input turns out to be okay. This approach is described in Chapter 18.