Spring web: how to validate form objects with Spring validator automatically at form submission


April 2019


336 time


I am using Spring validator for form validation. Here is the structure of my code. As you can see, I have to manually call validate in the POST method. Is there any way for me to wire the validator into the form processing without me calling validate()?

Please note that my domain object (MyModel) is a POJO without any field-level annotations such as @NotNull, etc.

Thanks a lot for help!

public class FormTest extends MyController {


    private MyValidator myValidator; // implementing Spring's Validator interface

    @RequestMapping(value={"/formtest"}, method=RequestMethod.GET)
    public String formGet(HttpServletRequest request, 
            @RequestParam(value="id", required = false) Long id,
            Map<String, Object> map) {
       return "/form";

    @RequestMapping(value={"/formtest"}, method=RequestMethod.POST)
    public String formPost(HttpServletRequest request, 
            @ModelAttribute("command") MyModel m,
            @RequestParam(value="id", required = false) Long id,
            Map<String, Object> map,
            BindingResult result, 
            SessionStatus status) {

            myValidator.validate(m, result); //manual validation
            if (result.hasErrors()) { 
                return "/form";

        return "redirect:/formtest?id=" + id;

    public MyModel backingObject(HttpServletRequest request, 
            @RequestParam(value="id", required = false) Long id) {
        MyModel m = null;
        if (id != null)
            m = service.getMyModel(id);
            m = new MyModel();
        return m;

1 answers


You can do it this way:

@RequestMapping(value = "/save", method = RequestMethod.POST)
public ModelAndView saveEntity(@Valid Entity entity, BindingResult result) {
    if (result.hasErrors()) {
           // do something
    // do something else

and also additional method is needed in the controller to register your validator:

public void initBinder(WebDataBinder binder) {
    binder.setValidator(new EntityValidator());