How can I tell the Data Annotations validator to also validate complex child properties?

Posted by GWB on Stack Overflow See other posts from Stack Overflow or by GWB
Published on 2010-03-22T16:10:09Z Indexed on 2010/03/22 16:21 UTC
Read the original article Hit count: 534

Filed under:
|
|

Can I automatically validate complex child objects when validating a parent object and include the results in the populated ICollection<ValidationResult>?

If I run the following 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<ValidationResult>();

            var isValid = Validator.TryValidateObject(person, validationContext, validationResults);

            Console.WriteLine(isValid);

            validationResults.ForEach(r => Console.WriteLine(r.ErrorMessage));

            Console.ReadKey(true);
        }
    }
}

I get the following output:

False
The Name field is required.

But I was expecting something similar to:

False
The Name field is required.
The State field is required.

© Stack Overflow or respective owner

Related posts about c#

Related posts about dataannotations