Shamil Puthukkot
Shamil Puthukkot

Reputation: 492

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;

}

Upvotes: 1

Views: 1084

Answers (2)

Shamil Puthukkot
Shamil Puthukkot

Reputation: 492

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

Upvotes: 1

levangode
levangode

Reputation: 426

You will need to create a custom validator class instead of using field annotations.

@Component
public class PayloadDTOValidator implements Validator {
    @Override
    public boolean supports(Class<?> clazz) {
        return PayloadDTO.class.equals(clazz);
    }
    
    @Override
    public void validate(Object target, Errors errors) {
        PayloadDTO payload = (PayloadDTO) target;

        //Retrieve path variable from request context
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String language = request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE).get("language");
        
        //Your validation logic
    }
}

Upvotes: 1

Related Questions