views:

248

answers:

1

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.

+1  A: 

You will need to make your own validator attribute (eg, [CompositeField]) that validates the child properties.

SLaks
This is the approach I am trying and it works, but I am hung up on the fact that the attribute can only return 1 ValidationResult. This is an issue if the child has multiple validation errors. I can stuff the error messages into a single string but it seems messy and wrong.
GWB
Any sample code you might be willing to share?
JC Grubbs