0

Is it possible to pass a value when using a custom annotated validation? The logic is different depending on the param value. In the example below, the chill room may require the key-value pairs to include "snack" : "" with max length 10, min length 1 similar to the @Size(min = 1, max = 10). I'm implementing the ConstraintValidator and set up the interface.

i.e.

@ConcertValidation(dressingRoom = "chill")
private List<Map<String, String>> json;
0

2 Answers 2

0

Inside the initialize method of the ConstraintValidator implementation, you can capture the value from annotation. For example:

class ConcertValidator implements ConstraintValidator<ConcertValidation, List<Map<String, String>>> {

    String dressingRoom;

    @Override
    public void initialize(ConcertValidation constraintAnnotation) {
        dressingRoom = constraintAnnotation.dressingRoom();
    }

    @Override
    public boolean isValid(List<Map<String, String>> value, ConstraintValidatorContext context) {
        boolean isValid = false;
        //TODO implement your logic depending on dressingRoom value
        return isValid;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

In the interface for the validator, include:

//default code
pubilc @interface ConcertValidation{
    // default code
    String dressingRoom() default "";
}

In the validator class, you must initialize the params you want to pass to use them in your logic for the isValid() method;

// global variables
private String dressingRoom;

@Override
public void initialize(ConcertValidation concertValidationConstraint){
    this.dressingRoom = concertValidationConstraint.dressingRoom();
}

Whenever you use the custom annotation validation, just pass the params.

@ConcertValidation(dressingRoom = "chill")
private List<Map<String, String>> json;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.