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.
Example:
public class ClassToValidate { @NotNull 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 { @ConstraintComposition(CompositionType.OR) @Null @Size(min =2, max=256) @Target({ElementType.METHOD, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = {}) public @interface EmailOrNull { String message() default "Not valid"; Class[] groups() default {}; Class[] payload() default {}; } @EmailOrNull private String email; }
I found some interesting information here:
JBOSS Hibernate validator documentation