Sokolof
Sokolof

Reputation: 2301

How to re-run Bean Validation on form object? (Spring 4 MVC controller)

I have simple model annotated with JSR-303

public class Article {
    ...
    @NotNull
    private String tag;
    ...
}

tag field is not exposed into form but instead is populated in controller's method

public class ArticleController {
   ...
   @RequestMapping(value = "/edit", method = PUT)
   public String doEdit(@Valid @ModelAttribute("article") final Article article,
                        final BindingResult bindingResult) {
    // generates article's tag, not editable by user
    article.setTag(generateTag(article));
    if (bindingResult.hasErrors()) {
        return "/edit";
    } else {
        service.save(article);
        return "redirect:/list";
    }
}

Right now bindingResult always has not null error on tag field since bean is validated before it is set. How can I re-validate article bean after tag filed is set and populate correct bindingResult?

Upvotes: 0

Views: 757

Answers (1)

Jose Luis Martin
Jose Luis Martin

Reputation: 10709

Try with

public class ArticleController {

    // inject the spring validator.
    @Autowired
    private LocalValidatorFactoryBean validator;

    @RequestMapping(value = "/edit", method = PUT)
    public String doEdit(@ModelAttribute("article") final Article article,
            final BindingResult bindingResult) {
        // generates article's tag, not editable by user
        article.setTag(generateTag(article));
        // validate
        validator.validate(article, bindingResult);

        if (bindingResult.hasErrors()) {
            return "/edit";
        } else {
            service.save(article);
            return "redirect:/list";
        }
    }
}

Upvotes: 2

Related Questions