Spring Boot - Custom validation annotation on form not working

aSemy

I'd like to have an annotation that validates that a MultipartFile is an image. I've created an @interface and a ConstraintValidator, and added the annotation to my field.

Other validation annotations, like @NotEmpty and @Size(min = 0, max = 2) are working fine.

Here is the code in summary. This question has the same problem, but the answer doesn't work for me.

Form.java:

@Validated
public class Form {

    @MultipartImage
    private MultipartFile image;

    ...
}

@Interface MultipartImage

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.LOCAL_VARIABLE;
import static java.lang.annotation.ElementType.METHOD;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

import validation.MultipartFileImageConstraintValidator;

@Documented
@Constraint(validatedBy = { MultipartFileImageConstraintValidator.class })
@Target({ LOCAL_VARIABLE, FIELD, METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface MultipartImage {

    String message() default "{MultipartImage.message}";

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

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

}

The validator, MultipartFileConstraintValidator.java

import java.io.IOException;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.springframework.web.multipart.MultipartFile;

public class MultipartFileConstraintValidator implements ConstraintValidator<MultipartImage, MultipartFile> {


@Override
public void initialize(final MultipartImage constraintAnnotation) {
}

@Override
public boolean isValid(final MultipartFile file, final ConstraintValidatorContext context) {
    return false;
}

Here's the form submit method in the controller

@RequestMapping(value = "/formsubmit", method = RequestMethod.POST)
public ModelAndView handleForm(@Validated final Form form,
        final BindingResult bindingResult) {

    if (bindingResult.hasErrors()) {
        ...
        // returns the model
    }
}

Validator set up in the @Configuration file, see https://stackoverflow.com/a/21965098/4161471

@Configuration
@ConfigurationProperties("static")
@AutoConfigureAfter(DispatcherServletAutoConfiguration.class)
public class StaticResourceConfig extends WebMvcConfigurerAdapter {

...

@Bean(name = "validator")
public LocalValidatorFactoryBean validator() {
    LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
    bean.setValidationMessageSource(messageSource());
    return bean;
}

@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
    final MethodValidationPostProcessor methodValidationPostProcessor = new MethodValidationPostProcessor();
    methodValidationPostProcessor.setValidator(validator());

    return methodValidationPostProcessor;
}

@Override
public Validator getValidator() {
    return validator();
}

@Bean
public ReloadableResourceBundleMessageSource messageSource() {
    ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
    // Load files containing message keys.
    // Order matters. The first files override later files.
    messageSource.setBasenames(//
            // load messages and ValidationMessages from a folder relative to the jar
            "file:locale/messages", //
            "file:locale/ValidationMessages", //
            // load from within the jar
            "classpath:locale/messages", //
            "classpath:locale/ValidationMessages" //
    );
    messageSource.getBasenameSet();
    messageSource.setCacheSeconds(10); // reload messages every 10 seconds
    return messageSource;
}

}

aSemy

There was information missing from my original code, specifically regarding the controller, where an additional validator is defined and bound. It uses the wrong method to include the validator FormValidator, and overrides the annotation validations.

binder.setValidator(formValidator) overrides any other validator. Instead binder.addValidators(formValidator) should be used!

@Controller
public class FormController {

     @Autowired
     final private FormValidator formValidator;

     @InitBinder("form")
     protected void initBinder(WebDataBinder binder) {
        // correct
        binder.addValidators(formValidator);
        // wrong
        //binder.setValidator(formValidator);
    }

    ...

    @RequestMapping(value = "/formsubmit", method = RequestMethod.POST)
    public ModelAndView handleForm(@Validated final Form form, final BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            ...
            // returns the model
        }
    ...
    }
}

I have also removed the Bean MethodValidationPostProcessor in the @Configuration class.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

html form validation using thymeleaf not working spring boot

From Dev

Transactional annotation not working in Spring Boot

From Dev

@Valid annotation is not working in spring boot

From Dev

form validation not performed, spring boot

From Java

Spring Boot - custom validation messages

From Dev

Spring MVC form validation not working

From Dev

Spring custom validation annotation + Validator implementation

From Dev

Spring MVC validator annotation + custom validation

From Dev

How to create a custom annotation in spring boot?

From Dev

django 1.8 custom validation of form not working

From Dev

Angular 5 form custom validation is not working properly

From Dev

Cannot get validation working with Spring Boot and Thymeleaf

From Dev

Spring Boot + JPA : @Transactional annotation : Roll back is not working

From Dev

Fine grained Spring autowiring not working (@Autowired with additional custom annotation)

From Dev

Fine grained Spring autowiring not working (@Autowired with additional custom annotation)

From Dev

Custom Annotation | Not working on setters

From Dev

Use ngModel on a custom directive with an embedded form, with working validation?

From Dev

Use ngModel on a custom directive with an embedded form, with working validation?

From Dev

Spring boot annotation confusion

From Dev

Spring boot @RequestMapping annotation

From Dev

Custom Validation Annotation introduces ConcurrentModificationException

From Dev

javax.validation 2.0.1 List<Object> not working in spring boot

From Dev

Spring @Value annotation not working

From Dev

Spring @Transactional annotation is not working

From Dev

Spring AOP Annotation not working

From Dev

@Qualifier Annotation in Spring is not working

From Dev

@Qualifier Annotation in Spring is not working

From Dev

Spring AOP Annotation not working

From Dev

Annotation not working in spring

Related Related

  1. 1

    html form validation using thymeleaf not working spring boot

  2. 2

    Transactional annotation not working in Spring Boot

  3. 3

    @Valid annotation is not working in spring boot

  4. 4

    form validation not performed, spring boot

  5. 5

    Spring Boot - custom validation messages

  6. 6

    Spring MVC form validation not working

  7. 7

    Spring custom validation annotation + Validator implementation

  8. 8

    Spring MVC validator annotation + custom validation

  9. 9

    How to create a custom annotation in spring boot?

  10. 10

    django 1.8 custom validation of form not working

  11. 11

    Angular 5 form custom validation is not working properly

  12. 12

    Cannot get validation working with Spring Boot and Thymeleaf

  13. 13

    Spring Boot + JPA : @Transactional annotation : Roll back is not working

  14. 14

    Fine grained Spring autowiring not working (@Autowired with additional custom annotation)

  15. 15

    Fine grained Spring autowiring not working (@Autowired with additional custom annotation)

  16. 16

    Custom Annotation | Not working on setters

  17. 17

    Use ngModel on a custom directive with an embedded form, with working validation?

  18. 18

    Use ngModel on a custom directive with an embedded form, with working validation?

  19. 19

    Spring boot annotation confusion

  20. 20

    Spring boot @RequestMapping annotation

  21. 21

    Custom Validation Annotation introduces ConcurrentModificationException

  22. 22

    javax.validation 2.0.1 List<Object> not working in spring boot

  23. 23

    Spring @Value annotation not working

  24. 24

    Spring @Transactional annotation is not working

  25. 25

    Spring AOP Annotation not working

  26. 26

    @Qualifier Annotation in Spring is not working

  27. 27

    @Qualifier Annotation in Spring is not working

  28. 28

    Spring AOP Annotation not working

  29. 29

    Annotation not working in spring

HotTag

Archive