JSF validation tutorial

Data validation is a key element of every application and JSF makes no exception to it. In this tutorial we will introduce the basic concepts of JSF validation using the tactics which are available since JSF 1.2 and the new validation options offered by JSF 2.0.

Data validation allow you to focus on business logic rather than the tedious qualifications of input data such as null checks, length qualifiers, range boundaries, etc.

Thus, it makes sense, then, that the validation processes happen before component data is bound to your backing bean model in the update model data lifecycle phase. The following picture shows the validation process in the JSF lifecycle.

jsf validation tutorial

The standard data validation

The standard data validation can be applied to allow restrictions on UIInputs. Basically you can apply to the fields to check that they are used in the correct range(minimum-maximum) and that they are not null


 <h:inputText id="name" value="#{sampleBean.userName}" >
  <f:validateLength minimum="5" maximum="20" />
 <h:inputText id="age" required="true"
  <f:validateLongRange minimum="18" maximum="50"/>
 <h:messages style="color:red" />
The above code will check for valid values of the "name" and "age" field, however it displays a generic error message which might not be fit for your purpose. In order to customize your messages, you need to add a message bundle element to your faces-config.xml

This will register the file ValidationMessages.properties as message bundle in your application.
Here are some possible attributes which you can set to define custom messages:
javax.faces.validator.LongRangeValidator.MAXIMUM={1}: Value is greater than allowable maximum of ''{0}''
javax.faces.validator.LongRangeValidator.MINIMUM={1}: Value is less than allowable minimum of ''{0}''
javax.faces.validator.LengthValidator.MAXIMUM={1}: Value is greater than allowable maximum of ''{0}''
javax.faces.validator.LengthValidator.MINIMUM={1}: Value is less than allowable minimum of ''{0}''
javax.faces.component.UIInput.REQUIRED={0}: Field required
javax.faces.validator.LongRangeValidator.NOT_IN_RANGE={2}: Field needs to be between the expected values of {0} and {1}
For the complete list of Message properties available check the Message.properties file which is packed in jsf-api-XX.jar (In JBoss 6 it's located in the <server>\deployers\jsf.deployer\Mojarra-2.0\jsf-libs    folder.

Follow us on Twitter