Validating User Input Using a Bean

If you think using JSTL to validate input looks complicated, you’re right. It works fine for simple validation, like making sure a value has a value at all (as for the Name field) or that a parameter has one of a few specific values (as for the Gender choice). But with more complex validation, such as verifying that a parameter holds an email address or a credit-card number, or that a value matches a list of valid values held in a database, we can do a lot better with a bean. In fact, the format of the Birth Date and Email Address fields, and if the Lucky Number is something else than a number, isn’t checked at all in the JSTL validation example. Other examples in this book will show how you can use custom actions to do more thorough validation of these types of values, but here we look at how it’s done using a bean. Figure 8-3 shows a typical response when some fields have invalid values.

Response generated for invalid input
Figure 8-3. Response generated for invalid input

Since a bean is implemented with Java code and has access to all Java APIs, it can do any kind of validation you can dream of. The UserInfoBean used in the previous bean example also has a number of validation properties, described in Table 8-8. If you’re curious about the bean implementation, it’s described in Chapter 20.

Table 8-8. Validation properties for com.ora.jsp.beans.userinfo.UserInfoBean

Property name

Get JavaServer Pages, 3rd 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.