Java Reference
In-Depth Information
Table 6-1. ( continued )
Annotation Type
Description
@Pattern
The annotated CharSequence must match the specified regular expression. The regular
expression follows the conventions of java.util.regex.Pattern .
@Size
The annotated element must be sided between the specified boundaries.
Supported Types:
CharSequence
Collection
Map
Array
What happens when you'd like to perform some validation that is not covered by one of the built-in constraint
annotations? Well, it is easy to build custom constraint annotations to incorporate validations that are not available
with the built-ins. Let's briefly review how this is done.
Suppose that employees in your organization have a customized employee identifier and want to include
validation to ensure that a given employee identifier complies with the standard for your organization. There are
a couple of ways to implement custom validation.
Implementing a managed bean method that has the task of performing validation
Validator class by implementing the javax.faces.validator.Validator
Creating a custom
interface
Review: Utilizing Different Validation Techniques
In this section, I will review how to implement validation for a form using both bean validation as well as a JSF
validator to compare the differences. The easiest way to write a custom JSF validator solution is to implement a
managed bean method that performs the validation. To do so, create a method that accepts three arguments.
FacesContext : The current context
UIComponent : The component being validated (must be of type UIInput )
Object : The value of the component being validated
The idea is that the value being passed into the method is validated against a custom constraint. If the validation
fails, the FacesContext is utilized to create a message, and the UIComponent 's valid attribute is set to null to indicate
that the validation has failed. Once the method has been created within a managed bean, it can be bound to a JSF
component via the component's validator attribute.
In the following example, method validation is used to process the value that is specified for an employee ID in a
UIInput component. If the value does not match the pattern constraint, then the validation fails. The validator method
in the following code excerpt is taken from a session-scoped JSF managed bean, org.javaee7.jsf.UsersBean :
public void validateUserId(FacesContext context,
UIComponent component,
Object value){
String idValue = (String) value;
 
Search WWH ::




Custom Search