Spring Boot MVC: validate a multipart/form-data RequestBody

Hello! I have the need to fill a form with some meta data and a file. The meta data required fields depends on the media "type" that you're selecting from a drop-down.

I've thus created a custom validator, associated to a custom annotation and put all on the PostMapping action annotating the parameter with @Valid @MyCustomAnnotation (see below). The thing is that the validator is not being called for a reason beyond my knowledge. May you please help me understand what I'm doing wrong?

Thank you very much ๐Ÿ™‚

The DTO + validator:
@Data
public class CreateMediaRequestResource {
    private MediaType mediaType;
    // TODO: various attributes depending on mediaType
    private MultipartFile media;

    @Documented
    @Constraint(validatedBy = CreateMediaRequestValidator.class)
    @Target({ElementType.PARAMETER})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface CreateMediaRequestValidation {
        public String message() default "";
        public Class<?>[] groups() default {};
        public Class<? extends Payload>[] payload() default {};
    }

    @Component
    public class CreateMediaRequestValidator implements ConstraintValidator<CreateMediaRequestValidation, CreateMediaRequestResource> {
        @Override
        public boolean isValid(CreateMediaRequestResource value, ConstraintValidatorContext context) {
            System.out.println(value);
            System.out.println(context);

            return false;
        }}
}


The controller's method:
// ...
public ResponseEntity<MediaMetadataResource> createMedia(
    @RequestBody @ModelAttribute
    @Valid @CreateMediaRequestValidation
    CreateMediaRequestResource data
) {
// this won't fail (and the validator won't print)


I've shortened the code as much as possible to stay in the chars limit, please ask me anything which might be related.

Thank you very much!
Was this page helpful?