JSR 303 – How to write a custom validator?

Bean validation specifications.

  1. JSR 349 is the specification for Bean Validation 1.1.
  2. JSR 303 is the specification for Bean Validation 1.0

Bean validation is an important task irrespective of the architecture (enterprise web application or thick client-server) of the application. JSR 303 specification standardize the bean validation process. JSR 303 is not intended for use in any one tier. It can be used in presentation tier or in persistence tier. JSR 303 defines a meta-data model and API for Java Bean validation. The default meta-data source is annotations, However you can override and extend the meta-data through the use of XML validation descriptors. In this post we will provide an example for complex custom validator. Please refer official documentation if you are interested to know about the standard validators. As I mentioned above JSR 303 and JSR 349 are specifications like JDBC or JNDI.

JSR 349 Implementations.

  1. Hibernate Validator

JSR 303 Implementations.

  1. Hibernate Validator
  2. Apache Bean Validation

Example Validator.

In our example we are using Bean Validation 1.0 (JSR 303). We need Java 6 or above to run this example.

Bean Validation 1.0 (JSR 303) Dependencies.

  1. validation-api-1.0.0.GA.jar
  2. hibernate-validator-4.2.0.Final.jar
  3. hibernate-validator-annotation-processor-4.2.0.Final.jar
  4. slf4j-api-1.6.1.jar

Maven dependencies.

Usecase for custom validator.

We are going to define a bean for Developer registration in a technology forum. If the developer claim that he has experience then the Employer field also must punched in. So the requirement shall be defined as..”if the experience filed value is greater than zero then the Employer field is required.”

Steps to write a custom validator.

  1. Write custom constraint annotation
  2. Write an implementation for the constraint

Custom constraint annotation.

Implementation for constraint.

Payload Bean.

Testcase for custom validator.