Arthur
Arthur

Reputation: 1548

Spring MVC: How to manually initiate validation later in controller method

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.

Upvotes: 1

Views: 6704

Answers (2)

Shafin Mahmud
Shafin Mahmud

Reputation: 4081

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

Upvotes: 3

Moshe Arad
Moshe Arad

Reputation: 3743

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();

Upvotes: 3

Related Questions