Java Reference
In-Depth Information
Chapter 4
Validating User Input
If you played around with the contact form that we created in the pre-
vious chapter, you probably realized that there is no validation on the
input. The user can enter just about any data on the form, or no input
at all, and submit it. The application will not complain about invalid or
missing values.
Adding validation to your forms is essential to recovering gracefully
from invalid input and keeping your model free of corrupted data. As
you'll see, Stripes gives you easy-to-use built-in validations and a sim-
ple way to gain full control for those more complex validations.
4.1
Stripes Validation Concepts
In Stripes, validations are defined with annotations in an action bean.
Using annotations gives you the advantage of being concise, compiled
(so you know right away if there's a typo), and autocompleted by IDEs.
Best of all, your validation rules are defined right there next to the
property, not off in some separate template or configuration file.
To add validation to an action bean property, annotate it with @Validate .
@Validate annotations
work only when used in
an action bean.
You can annotate either the field (even if it is private), the getter method,
or the setter method associated to the property. Using attributes of
@Validate , you specify the validation criteria.
Let's look at a simple example. Suppose we have an age property in an
action bean and a corresponding text field in a form. We could make
this field required and validate that the age entered by the user is at
least eighteen, with this annotation:
@Validate(required= true , minvalue=18)
private Integer age;
 
 
 
 
Search WWH ::




Custom Search