Add Custom Validation Annotation for a Parameter in Controller - JSR-303

Viewed 2189

I can't figure out how to resolve the following use case in Spring Boot. Indeed, I have a Spring Boot Rest Api (eg: user-api) with the following controller method with a custom validator for a parameter :

@PostMapping
   public User createUser(@ValidZipCode @RequestBody @Valid User user){
       return userService.saveUser(user);
   }

The User Class is defined in an external dependency (eg: user-model). It has the following fields :

public class User {
   @NotNull
   private String firstName;
   @NotNull
   private String lastName;
   private String zipCode;
   // getters, setters ..
}

In, user-api I created the following custom annotation :

@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = ZipCodeValidator.class)
public @interface ValidZipCode {

    String message() default "Must be a valid zipCode. Found: ${validatedValue}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};

}

And so the ZipCodeValidator implementation :

public class ZipCodeValidator implements ConstraintValidator<ValidZipCode, User> {
private ZipCodeService zipCodeService;

@Override
public void initialize(ValidZipCode constraintAnnotation) { }

@Override
public boolean isValid(User user, ConstraintValidatorContext constraintValidatorContext) {
    return !Objects.isNull(user.getZipCode()) ?
            zipCodeService.isValidZipCode(user.getZipCode()) :
            false;
}

NB: zipCodeService.isValidZipCode() is a simple boolean method.

The problem is that when I call the endpoint it never access the @ValidZipCode annotation. Is there any bean configuration to set up to make it works ?

Thks for your help ;)

UPDATE

Thanks to @cassiomolin for his answer. Indeed, when I annotate the controller class with @Validated It works :D

I Hope this post will help other devs ;)

1 Answers

Ensure that your controller class is annotated with @Validated.

See the following quote from the documentation:

To be eligible for Spring-driven method validation, all target classes need to be annotated with Spring’s @Validated annotation [...]

Related