Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use an annotation element inside a custom constraint validator

I wrote a custom annotation in my project called CGC:

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = CGCValidator.class)
public @interface CGC {
    String message() default "{person.cgc.error}";

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

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

    boolean canBeNull() default false;

    @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
    @Retention(RUNTIME)
    @Documented
    public @interface List {
        CGC[] value();
    }
}

I have a validator class that uses the annotation and basically, as my first validation I wanna check if the field is null, but only If the annotation for that field has specified the "canBeNull" element as true (@CGC(canBeNull="true")). My question is: how can I access the canBeNull element inside my validator class?

*The validator should be something like this:

public class CGCValidator implements ConstraintValidator<CGC, String> {

    @Override
    public void initialize(CGC annotation) {
    }

    @Override
    public boolean isValid(String cgc, ConstraintValidatorContext constraintValidatorContext) {
    if(!canBeNull() && cgc == null) {
    return false;
    }
    ...
like image 459
chr0x Avatar asked Oct 28 '25 05:10

chr0x


1 Answers

You can capture the canBeNull value in the initialize function:

class CGCValidator implements ConstraintValidator<CGC, String> {

    boolean canBeNull;

    @Override
    public void initialize(CGC constraintAnnotation) {
        canBeNull = constraintAnnotation.canBeNull();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        return canBeNull || value != null;
    }
}
like image 162
bm1729 Avatar answered Oct 31 '25 01:10

bm1729



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!