Announcement Announcement Module
No announcement yet.
Where do add additional logic for validation that makes db calls? Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Where do add additional logic for validation that makes db calls?

    My create controller method looks like this:

     @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
    Now my accountForm class has simple validations on the fields like NotNull, Size, Pattern, etc. For example:

       @NotNull(message = "Email cannot be empty.")
        @Size(min=3, max=20, message="Email must be between 3 and 100 characters long.")
        private String email;
    What if I need to make a database call? e.g. to make sure the email address is not a duplicate, etc.

    I'm planning on doing this for now:

    if(!bindingResult.hasErrors()) {
       if(userService.doesEmailExist(accountForm.getEmail())) {
          bindingResult.addError(new ObjectError("email", "Email address already exists."));   
    But I don't like this approach since the validation logic in not encapsulated in a single place.
    Is there a better way?