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

StackOverflow https://stackoverflow.com/questions/16500271

  •  21-04-2022
  •  | 
  •  

Question

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!

@Controller
public class FormTest extends MyController {

    .....

    @Autowired
    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";
            }

        service.saveMyModel(m);       
        return "redirect:/formtest?id=" + id;
    }

    @ModelAttribute("command")
    public MyModel backingObject(HttpServletRequest request, 
            @RequestParam(value="id", required = false) Long id) {
        MyModel m = null;
        if (id != null)
            m = service.getMyModel(id);
        else
            m = new MyModel();
        return m;
    }
}
Was it helpful?

Solution

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:

@InitBinder("entity")
public void initBinder(WebDataBinder binder) {
    binder.setValidator(new EntityValidator());
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top