Search code examples
javaspring-bootspring-validatorspring-validation

How to pass the value from Pathvariable to a custom Validator in springboot?


I am having a custom Validator as follows:

@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = CountryValidator.class)
public @interface ValidCountry {

    String message() default "Invalid country";

    String language() default "";

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


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

public class CountryValidator implements ConstraintValidator<ValidCountry, String> {

  

    @Override
    public void initialize(ValidCountry constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
    }

    @Override
    public boolean isValid(String inputCountry, ConstraintValidatorContext constraintValidatorContext) {
        //validation logic
    }

}

And the controlller method

 @PutMapping("/operation/{language}")
    @ResponseStatus(HttpStatus.OK)
    public ResponseEntity<Object> doOperation(@PathVariable("language") String language, @Valid @RequestBody PayloadDTO payload) {


        System.out.println("Done");
        return ResponseEntity.accepted().body(null);
    } 

Now i want to validate a field inside PayloadDTO using @ValidDate annotation. And i want the language to be taken from the Pathvariable. Is there anyway to achieve this? Something like this

PayloadDTO{

@ValidCountry(language = <language from pathvariable>)
private String country;

}

Solution

  • This was achieved by autowiring HttpServletRequest bean in validator class and fetching pathvariable from the bean.