title: Recursive validation using annotations and IValidatableObject
body: <p>I am trying to validate nested objects (not models in the MVC senss) using annotations and some custom code.</p>
  
  <p>I found the following post useful</p>
  
  <p><a href="https://stackoverflow.com/questions/6938877/using-data-annotations-validation-manually-and-object-graphs">Using Data Annotations Validation Manually and Object Graphs</a></p>
  
  <p>As suggested in an answer, I've created an extra routine in the container class to validate the nested object. Here's my modified test code</p>
  
  <pre><code>public class Customer : IValidatableObject
  {
      public Customer()
      {
          Details = new CustomerDetails();
      }
  
      [Required]
      [MaxLength(2)]
      public string Name
      {
          get;
          set;
      }
  
      public CustomerDetails Details
      {
          get;
          private set;
      }
  
      public IEnumerable&lt;ValidationResult&gt; Validate(ValidationContext validationContext)
      {
          var context = new ValidationContext(this.Details, validationContext.ServiceContainer, validationContext.Items);
          var results = new List&lt;ValidationResult&gt;();
          Validator.TryValidateObject(this.Details, context, results);
          return results;
      }
  }
  </code></pre>
  
  <p>However I have problems getting <em>all</em> the validation errors, even when calling TryValidateObject with validateAllProperties set to true. </p>
  
  <pre><code>        var context = new ValidationContext(cs, null, null);
          var results = new List&lt;ValidationResult&gt;();
          Validator.TryValidateObject(cs, context, results,true);
  </code></pre>
  
  <p>If there are any errors in the container, only these will show. Only when there are no errors in the container object, errors in the nested object will show. I suspect it has something to do with the Validate rouine returning a full list, and not being able to add to an (existing) list from the container(?)</p>
  
  <p>Are there any modifications I can make to routine to get all errors to show?</p>