My create controller method looks like this:
Now my accountForm class has simple validations on the fields like NotNull, Size, Pattern, etc. For example:Code:@RequestMapping(value = "/create", method = RequestMethod.POST) public ModelAndView create(@Valid AccountForm accountForm, BindingResult bindingResult) { ModelAndView mav = new ModelAndView("accounts/new"); mav.addObject("errors", bindingResult.getAllErrors()); mav.addObject("accountForm", accountForm); if (bindingResult.hasErrors()) { return mav; } // more code here }
What if I need to make a database call? e.g. to make sure the email address is not a duplicate, etc.Code:@NotNull(message = "Email cannot be empty.") @Size(min=3, max=20, message="Email must be between 3 and 100 characters long.") private String email;
I'm planning on doing this for now:
But I don't like this approach since the validation logic in not encapsulated in a single place.Code:if(!bindingResult.hasErrors()) { if(userService.doesEmailExist(accountForm.getEmail())) { bindingResult.addError(new ObjectError("email", "Email address already exists.")); } }
Is there a better way?


Reply With Quote
