title: Spring MVC and JSR-303 hibernate conditional validation
body: <p>I've a form I want to validate. It contains 2 Address variables. address1 has always to be validated, address2 has to be validated based on some conditions</p>
  
  <pre><code>public class MyForm {
      String name;
      @Valid Address address1;
      Address address2;
   }
  
  public class Address {
      @NotEmpty   
      private String street;
  }
  </code></pre>
  
  <p>my controller automatically validates and binds my form obj</p>
  
  <pre><code>@RequestMapping(...)
  public ModelAndView edit(
          @ModelAttribute("form")
          @Valid
          MyForm form,
          BindingResult bindingResult,
          ...)
  
          if(someCondition) {
              VALIDATE form.address2 USING JSR 303
  </code></pre>
  
  <p>the problem is that if I use the LocalValidatorFactoryBean validator i can't reuse the BinidingResult object provided by Spring. The bind won't work as the target object of 'result' is 'MyForm' and not 'Address'</p>
  
  <pre><code>validate(form.getAddress2(), bindingResult)   //won't work
  </code></pre>
  
  <p>I'm wondering what's the standard/clean approach to do conditional validation.</p>
  
  <p>I was thinking in programmatically create a new BindingResult in my controller. </p>
  
  <pre><code>final BindingResult bindingResultAddress2 = new BeanPropertyBindingResult(address2, "form");
  validate(form.getAddress2(), bindingResultAddress2);
  </code></pre>
  
  <p>but then the List of errors I obtain from bindingResultAddress2 can't be added to the general 'bindingResult' as the field names are not correct ('street' instead of 'address2.street') and the binding won't work.</p>
  
  <p>Some dirty approach would be to extend BeanPropertyBindingResult to accept some string to append to the fields name.. do you have a better approach?</p>