JSF validation model defines a set of standard classes for validating the UI components. The JSF library defines a group of core tags that corresponds to javax.faces.validator.Validator implementations. Apart from the standard error messages validation model allows us to define the custom validations. Validations in JSF can be categorized into Imperative and Declarative.

JSF Validation – Declarative Validator

The validations that are fired using JSF standard validators or Bean validators fall under declarative type.

Examples for JSF standard validators are Length validator, Required validator etc..

Consider an example for standard validator. Create mobile.xhtml as

mobile.xhtml

Here we are setting the required attribute to true which makes the field mandatory and fires the custom message “value is required” for color field and user defined message for mobile name field as the message is specified in the requiredmessage attribute.

Run the application and you will see the below output on pressing submit button.

JSF-Validation-Model-1-450x305

JSF Imperative validation

The standard validation messages would not be sufficient in all the cases and sometimes may require complex validations.Imperative validation allows users to do this by

  1. Firing the validation from the Bean method
  2. Use annotation @FacesValidator in the class during runtime

Firing the validation from the Bean method
In this type of validation we write a method in the bean to validate the UIComponents and invoke this method from the jsf page through a validator attribute in the inputText tag.

Now lets see consider an example of firing a validation from the Bean.

mob.xhtml

In this page we are invoking the validateModelno method of the java bean in the validator tag attribute.

Create Mobile.java as

Here we are checking for the length of the model no and if the length is less than 4 we are specifying the message as “Minimum length of model number is 4”.

Now Run the application which produces the following output.

JSF-Validation-Model-2-450x201

Using @FacesValidator in the Bean – Custom JSF Validator

In this method we use @FacesValidator annotation, specify the name for the validator and implement the Validator by overriding the validate method.

mobvalidator.xhtml

In this we are calling the custom validator named “mobileValidator” in the validatorId attribute of the <f:validator> tag.

Create MobileValidator.java as

Here we override the standard validate method and implement our own logic for validating the input fields.

Run the application and see the output as shown below.

JSF-Validation-Model-3-450x163

Finally below image shows the project structure.

JSF-Validation-Model-Project

You can download the project from below link and play around with it to learn more.

By admin

Leave a Reply

%d bloggers like this: