title: Using Spring MVC Validator in controller using multiple domain objects
body: <p>I have a Spring MVC controller that handles requests to do with user management including a method to save user details and a method to allow a user to reset their password. I want to use a validator to ensure that the user typed the same password twice.</p>
  
  <p>My controller</p>
  
  <pre><code>@Controller
  public class UserDetails {
  ...
  @InitBinder
  public void binder(WebDataBinder binder) {
      binder.addValidators(new PasswordValidator());
  }
  ...
  @RequestMapping(value="/saveUserDetails", method=RequestMethod.POST)
  public String saveUserDetails(
      @ModelAttribute User user) {
      ...
  }
  ...
  @RequestMapping(value="/resetPassword", method=RequestMethod.POST)
  public String resetPassword(
      @Validated PasswordPair password, BindingResult result) {
      ...
  }
  </code></pre>
  
  <p>And the Validator</p>
  
  <pre><code>    private final static class PasswordValidator implements Validator {
  
      private final static int MIN_LEN=5;
  
      @Override
      public boolean supports(Class&lt;?&gt; clazz) {
          return PasswordPair.class.isAssignableFrom(clazz);
      }
  
      @Override
      public void validate(Object target, Errors errors) {
          PasswordPair pair = (PasswordPair)target;
          //1 impose password rules
          if (pair.getPassword().length()&lt;MIN_LEN) {
              errors.rejectValue("password", "Too short", "Password must bne at least "+MIN_LEN+" chars");
          }
          if (!pair.getPassword().equals(pair.getConfirmPassword())) {
              errors.rejectValue("confirmPassword", "mustMatch", "passwords must match");
          }
      }
  
    }
  </code></pre>
  
  <p>The problem is that when saveUserDetails is called spring is trying to validate the user with the password validator.</p>
  
  <p>I have tried changing <code>@InitBinder</code> to <code>@InitBinder("password")</code> or <code>@InitBinder("PasswordPair")</code> but in that case nothing is validated at all.</p>
  
  <p>How can I make it validate only the correct parameters?</p>