title: How can I validate a field of a object on my domain object in Spring MVC?
body: <p>I have an object <code>Foo</code> that holds a reference to object <code>Bar</code> that has a reference to object <code>Baz</code>, and in order for <code>Foo</code> to be valid, <code>Bar</code> has to have a valid, non-null reference to <code>Baz</code>.</p>
  
  <p>The problem is that <code>Bar</code> <em>doesn't</em> require a valid, non-null <code>Baz</code> to be valid, so I can't simply put the validation in there, I need it to be within <code>Foo</code>.</p>
  
  <p>Here's a simple pseudo-version of the class structure I'm talking about:</p>
  
  <pre><code>class Foo {
      // Bar needs to have a valid Baz. Something like this would be ideal:
      // @HasAValidBaz(message="Baz is required")
      Bar bar;   
  }
  
  class Bar {
      // Baz can be null and Bar will still be valid
      // But if there _is_ a Baz, it needs to be valid
      Baz baz;
  }
  
  class Baz {
      @NotBlank(message="My String is required")
      String myString;
  }
  </code></pre>
  
  <p>I know I can do this with class-level custom validation annotations, but the problem is that those error objects and corresponding messages apply to the class instance and not the field instance, which I need to be able to easily display the error message next to the correct form field.</p>
  
  <p>Is there a good way to do this, or am I stuck with implementing this validation in the controller?</p>