1

I have a controller method that receives a command object containing a list of objects annotated for validation. However, completely empty items should be ignored so I cannot use @Valid in controller method header because it would generate an error for all fields of all list items.

I would like to remove the empty lines from the list and call the Spring validator after. How can I do that?

This is a Spring Boot project.

Arthur
  • 1,478
  • 3
  • 22
  • 40
  • 1
    Please check this post, think there is appropriate example http://stackoverflow.com/questions/19190592/manually-call-spring-annotation-validation – Stan Oct 05 '16 at 14:07
  • I remember finding this earlier I failed to use it. Trying to inject SmartValidator results in No qualifying bean found for dependency [org.springframework.validation.SmartValidator]: expected at least 1 bean which qualifies as autowire candidate. And trying to inject Spring's Validator fails because of finding too many beans, including my custom validators. – Arthur Oct 05 '16 at 14:14
  • OK, managed to inject by using `@Autowired @Qualifier("mvcValidator") Validator mvcValidator;` – Arthur Oct 05 '16 at 14:28

2 Answers2

3

This is a spring example of how to do validation without the @valid annotation:

Foo target = new Foo();
DataBinder binder = new DataBinder(target);
binder.setValidator(new FooValidator());

bind to the target object

binder.bind(propertyValues);

validate the target object

binder.validate();

get BindingResult that includes any validation errors

BindingResult results = binder.getBindingResult();
Moshe Arad
  • 3,587
  • 4
  • 18
  • 33
3

May be its late. But it could come help with others.

Actually you need LocalValidatorFactoryBean in your context to explicitly call the validator. In your any context you could decalre the bean like

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
     <property name="validationMessageSource" ref="messageSource"/>
</bean>

In your controller Autowire the bean and call explicitly for validate() method

    @Autowired
    private Validator validator;

    @Autowired
    private MyCustomValidator customValidator;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.addValidators(smartValidator, customValidator);
    }

    public String save(@ModelAttribute FooModel foo, BindingResult result) {
        // ... your cutom logic and processing
        validator.validate(foo, bindingResult);
        customValidator.validate(foo, bindingResult);
        if (result.hasErrors()) {
            // ... on any validation errors
        }

        return "view";
    }

You could go through this for more about this scenario

Shafin Mahmud
  • 3,831
  • 1
  • 23
  • 35