creating custom constraints

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

We’ve seen how to use constraints in bean validation in previous post. But what if we want some constraints which validate our own requirement? Java provides a way of creating custom constraints for bean validation.

Creating Custom Constraints:

While creating custom constraints, two components are needed.

  • Annotation to be specified as constraint
  • An implementing class which has validation logic.

Consider a situation in which we are organizing a cricket match series and a series can contain only odd number of matches. Obviously we should look into creating custom constraints for such requirement. So we will create a constraint called @Odd which will be composed of an annotation and implementing class.

Let us understand what above code means:

  • @Target annotation specifies that @Odd can be applied to fields and method by specifying @Target({ ElementType.METHOD, ElementType.FIELD })
  • @Retention(RetentionPolicy.RUNTIME) specifies how long annotations are retained, in this case, they are retained till runtime.
  • @Constraint(validatedBy = { OddNumberValidator.class }) specifies the validator class that should be used in creating custom constraints for odd number
  • String message() default "Number must be Odd"; specifies the message when validation fails.

 

Now creating custom constraints also needs an implementing class.

  •   OddNumberValidator implements ConstraintValidator<Odd, Integer>  The class needs to implement ConstraintValidator interface with the first parameter as the annotation which will be used for validation and another parameter is the type that needs to be validated, in our case, it is Integer.
  • initialize() method can be used to access attributes from the validator annotation interface. In our case it was not needed.
  • isValid method specifies logic for validation. we want to return true if the number is odd.

Let us try this out. We have a bean called Series having noOfMatches as its fields annotated as @Odd

Invoke the validation using code below.

This prints out validation message.

noOfMatches  Number must be Odd

I hope this example helped understand creating custom constraints for validation.

References for further study :

 

 

Share Button

Prasad Kharkar

Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Leave a Reply

Your email address will not be published. Required fields are marked *