How to add conditions to Java Bean validation?

Today I faced a very common problem and I did not find out how to solve it for some time. I am using Java Beans Validation (JSR 380), so this means that I can use annotations in my class and at the time of validation, my framework (in this case Springboot) is automatically trying to validate the values of the class.

public class ClassToValidate {
  private String email;

This works fine, and I can add annotations like:

  • @NotNull
  • @Size(min = 2, max = 64)
  • etc…

But my problem was that I wanted to have a special kind of validation:

  • If the field is null, this is ok for me.
  • But if the field is not null, then I want to add special validation (like checking that the minimal and maximal length of the string is validated and is between 2 and 64 chars).

The Java Beans validation provides a very helpful way how to create custom annotations, and this is what is needed to have such a conditional (OR) validation logic. Just create your own annotations, and combine them using OR:

public class ClassToValidate {
    @Size(min =2, max=256)
    @Target({ElementType.METHOD, ElementType.FIELD})
    @Constraint(validatedBy = {})
    public @interface EmailOrNull {
        String message() default "Not valid";

        Class[] groups() default {};

        Class[] payload() default {};

    private String email;

I found some interesting information here:
JBOSS Hibernate validator documentation

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.