Bean validation (JSR 303) is a new feature that is available in Java EE 6. A JavaServer Faces 2.0 implementation must support bean validation if the server runtime (such as Java EE 6) requires it.
Validation can take place at different layers in even the simplest of applications, as shown in the guessNumber example application from the earlier chapter. The guessNumber example application validates the user input (in the <h:inputText> tag) for numerical data at the presentation layer and for a valid range of numbers at the business layer.
The bean validation model is supported by constraints in the form of annotations placed on a field, method, or class of a JavaBeans component such as a backing bean.
Constraints can be built-in or user-defined. Several built-in annotations are available in the javax.validation.constraints package. Some of the commonly used built-in annotations are listed below:
@Min: The annotated element must be a number whose value must be higher or equal to the specified minimum.
@Max: The annotated element must be a number whose value must be lower or equal to the specified maximum.
@Size: The annotated element must be between specified minimum and maximum boundaries.
@NotNull: The annotated element must not be null.
@Null: The annotated element must be null.
@Pattern: The annotated element must match the specified Java regular expression.
For a complete list of built-in constraint annotations, see API documentation for javax.validation.constraints class at http://java.sun.com/javaee/6/docs/api/.
In the following example, a constraint is placed on a field using the built-in @NotNull constraint:
public class Name { @NotNull private String firstname; @NotNull private String lastname; }
You can also place more than one constraint on a single JavaBeans component object. For example, you can place an additional constraint for size of field on the first name and the last name fields:
public class Name { @NotNull @Size(min=1, max=16) private String firstname; @NotNull @Size(min=1, max=16) private String lastname; }
The following example shows a user-defined constraint placed on a method which checks for a predefined email address pattern such as a corporate email account:
@validEmail public String getEmailAddress() { return emailAddress; }
A user-defined constraint also needs a validation implementation. For a built-in constraint, a default implementation is already available. Any validation failures are gracefully handled and can be displayed by h:messages tag.