title: Using JSR-303 annotations for conditional validation in Spring MVC
body: <p>I have a form with ten fields, but a page displays only five fields initially. Remaining fields are hidden, and show up based on onChange event listener bound to other field. </p>
  
  <p>There are scenarios wherein it is possible to submit a form with just five not blank fields. In that case, validation has to be performed only for those five. Sometimes, validation has to be performed for all fields (based on the state of that other field with onChange callback). Is there a way to filter field validation using annotations or should I write a custom validator?</p>
  
  <p>Right now all ten form fields are validated. 
  The rules are the following:</p>
  
  <ul>
  <li>a,b,c,d,e are mandatory fields</li>
  <li>f,g,h shows up only if a="111"</li>
  <li>i,j shows up only if c="222"</li>
  </ul>
  
  <p>Sample code:</p>
  
  <pre><code>@NotBlank
  private String a;
  @NotBlank
  private String b;
  @NotBlank
  private String c;
  @NotBlank
  private String d;
  @NotBlank
  private String e;
  
  @NotBlank(a="111")
  private String f;
  @NotBlank(a="111")
  private String g;
  @NotBlank(a="111")
  private String h;
  @NotBlank(c="222")
  private String i;
  @NotBlank(c="222")
  private String j;
  </code></pre>
  
  <p>Controller code:</p>
  
  <pre><code>@RequestMapping(value="/payments/getTax.do", method=RequestMethod.POST) 
  public String getTaxInfo(@Valid OneTimeForm command, BindingResult result, 
      Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {        
  
  
  OneTimeForm oneTimeForm = (OneTimeForm) command;        
  
  try {
      validator.validate(oneTimeForm, result);
  } catch (ValidationException ex) {  
      throw ex;
  }
  ...///
  </code></pre>