Home > Mobile >  Can I create custom validation annotation that inherits from javax.constrains annotations
Can I create custom validation annotation that inherits from javax.constrains annotations

Time:10-11

I'm wondering if it's possible to do something like:

@Min(1)
@Max(100)
public @interface ValidationForX {}

and then

@ValidationForX
int X;

For some reason @Min and @Max are applicable on annotations so I'm assuming it should be possible

I want to hide this validation behind one annotation because I want to reuse it

Thanks for your help!

CodePudding user response:

You annotation must look like this:

@Min(1)
@Max(100)
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {})
public @interface ValidationForX {

    String message() default "value should be greater or equal than 1 and less or equal than 100.";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

Read more about composing constraints here: https://www.baeldung.com/java-bean-validation-constraint-composition

CodePudding user response:

You can directly use @Min and @Max annotation on top of the field which you want to validate. Something like this:

@Max(value=100)
@Min(value=1)
int X;
  • Related