JSF 2 Custom Validator Example with @FacesValidator Annotation

By Arvind Rai, January 21, 2015

This page will provide demo for JSF 2 Custom Validator. We need to do two simple steps to create custom validator in JSF 2. First step is that create a class implementing javax.faces.validator.Validator interface and override validate method. Annotate this class by @FacesValidator in which we assign a validator-id. Second step is that use the validator id in UI by f:validator tag.

Project Structure in Eclipse

Find the project structure in eclipse.

Create a Custom Validator Class

@FacesValidator: Using this annotation, the validator class is automatically registered to runtime. We need to assign a validator id which will be used in view creation for validation.
javax.faces.validator.Validator: Implement Validator interface and override validate() method. For failed validation condition, create a class FacesMessage with validation message and throw ValidatorException.

For the example, we are creating an email validator.
EmailValidator.java

Output

Download the source code and create war file. Deploy it and access by URL http://localhost:8080/JSF2Demo-1/user.xhtml, We will find the below web page. When we enter wrong email id and click on submit button, message for validation will be displayed.