Search code examples
springspring-bootvalidationcustomvalidator

How to create a custom annotated validation that has a param in spring boot?


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;

Solution

  • 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;