JSF 2 and Bean validation


The Bean Validation JSR (JSR-303) defines a generic, tier-independent mechanism for specifying data validation constraints. The specification includes several standard constraint annotations (eg. @NotNull, @Size, @Min, @Max, etc…) and also allows custom constraints to be defined.

JSF 2 provides built-in integration with JSR-303 constraints. When you are using bean validation in your application, JSF automatically uses the constraints for beans that are referenced by UIInput values.

Example:

package sample;

import javax.faces.bean.*;
import javax.validation.constraints.*;

@ManagedBean
@RequestScoped
public class SampleBean {

 @Size(min = 1, message = "Please enter the Email")
 @Pattern(regexp = "[a-zA-Z0-9]+@[a-zA-Z0-9]+\\.[a-zA-Z0-9]+", message = "Email format is invalid.")
 private String email;

 @Size(min = 5, max=20, message = "Please enter a valid username (5-20 characters)")
 private String userName;

 @Size(min = 5, max = 20, message = "Please enter a valid password (5-10 characters)")
 private String password;

 // getter and setters methods here
 
}

By default, the Bean Validator is enabled, therefore our JSF pages do not need to contain any info about the Bean Validator. When validation constraints fail, any associated error messages are automatically translated into FacesMessages by the JSF implementation.

You can however disable the validator for any field of the ManagedBean
<h:inputText value="#{sampleBean.userName}">
 <f:validateBean disabled="true" />
</h:inputText>


In addition, the validationGroups attribute may be used to manually specify which validation groups should be taken into account when validating a particular component:
 @Size(min = 1, message = "Please enter the Email",groups = sample.MyGroup.class )
 @Pattern(regexp = "[a-zA-Z0-9]+@[a-zA-Z0-9]+\\.[a-zA-Z0-9]+", message = "Email format is invalid.")
 private String email;

 @Size(min = 5, max=20, message = "Please enter a valid username (5-20 characters)",groups = sample.MyGroup.class)
 private String userName;

 @Size(min = 5, max = 20, message = "Please enter a valid password (5-20 characters)",groups = sample.MyGroup.class)
 private String password;
 

Here sample.MyGroups is just a place holder interface which is used to define the group of fields.
Then you can reference the validation groups as follows:
 <h:inputText value="#{sampleBean.userName}">
  <f:validateBean validationGroups="sample.MyGroup.class "/>
 </h:inputText>

 

0
0
0
s2smodern