Validate entities that contains entities with validation attributes

Topics: Validation Application Block
May 14, 2010 at 11:06 AM

Hi:

 

I have a problem with Validation block and I don't know how to resolve, this is the example:

namespace ConsoleApplication1
{
    public class Citizen
    {
        #region Properties

        /// <summary>
        /// Gets or sets FirstName.
        /// </summary>
        [StringLengthValidator(1, 50,
               MessageTemplate = "First Name must be between 1 and 50 characters")]
        public string FirstName { get; set; }

        #endregion
    }

    public class Case
    {
        #region Properties

        public Citizen Citizen { get; set; }

        #endregion
    }

    class Program
    {
        static void Main(string[] args)
        {
            Case Case = new Case
            {
                Citizen = new Citizen()
                {
                    FirstName = "a"
                }
            };

            var validator = ValidationFactory.CreateValidatorFromAttributes<Case>();

            Console.WriteLine(validator.Validate(Case).IsValid);

            Console.Read();
        }
    }
}

The result of the program execution is True but Case contains a Citizen class that is not valid and the result must be false, isn't it?

Is necessary need specify somo attribute to the field Citizen? How does run this kind of validation?

Thanks!!!

May 16, 2010 at 11:31 PM

You need to associate an ObjectValidator to the Citizen property of the Case class.  You can do this through config or by decorating it with the ObjectValidator attribute.  If you're using 4.1 or lower versions, you do this:

[ObjectValidator(typeof(Citizen))]

If you're using the 5.0 version, you need not specify the type:

[ObjectValidator()]

As additional information, for collection types of properties, you can use ObjectCollectionValidator.

[ObjectCollectionValidator()]

public List<Citizen> Citizens { get; set; }

 

Sarah Urmeneta
Global Technology and Solutions
Avanade, Inc.
entlib.support@avanade.com