Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Thanks for your help!

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading