Showing posts from April, 2016

Spring MVC: Trgger manual validation of a form object

Sometimes it may be needed to use manual validation in Spring MVC @Controller. This is very simple with Spring’s org.springframework.validation.ValidationUtils class. Learn how to invoke a validator in two different scenarios. Scenario 1 - invoke validation In this scenario, I have a user form with username field. Username field is validated with custom validator in order to verify the existance in e.g. database. public class User { @UserExists private String username; } In controller class I have a method that handles POST method of that object: @Autowired private org.springframework.validation.Validator validator; @RequestMapping(value = "/user", method = RequestMethod.POST) public String validate(@ModelAttribute User user, Errors errors) { ValidationUtils.invokeValidator(validator, user, errors); if (errors.hasErrors()) { // error, show errors to the user } // success, form is valid! } org.springframework.validatio