Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I tell the Data Annotations validator to also validate complex child properties?
    primarykey
    data
    text
    <p>Can I automatically validate complex child objects when validating a parent object and include the results in the populated <code>ICollection&lt;ValidationResult&gt;</code>?</p> <p>If I run the following code:</p> <pre><code>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace ConsoleApplication1 { public class Person { [Required] public string Name { get; set; } public Address Address { get; set; } } public class Address { [Required] public string Street { get; set; } [Required] public string City { get; set; } [Required] public string State { get; set; } } class Program { static void Main(string[] args) { Person person = new Person { Name = null, Address = new Address { Street = "123 Any St", City = "New York", State = null } }; var validationContext = new ValidationContext(person, null, null); var validationResults = new List&lt;ValidationResult&gt;(); var isValid = Validator.TryValidateObject(person, validationContext, validationResults); Console.WriteLine(isValid); validationResults.ForEach(r =&gt; Console.WriteLine(r.ErrorMessage)); Console.ReadKey(true); } } } </code></pre> <p>I get the following output:</p> <blockquote> <p><code>False</code><br> <code>The Name field is required.</code></p> </blockquote> <p>But I was expecting something similar to:</p> <blockquote> <p><code>False</code><br> <code>The Name field is required.</code><br> <code>The State field is required.</code></p> </blockquote> <hr> <p>I offered a bounty for a better child object validation solution but didn't get any takers, ideally</p> <ul> <li>validating child objects to an arbitrary depth</li> <li>handling multiple errors per object</li> <li>correctly identifying the validation errors on the child object fields.</li> </ul> <p>I'm still surprised the framework doesn't support this.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload