Validation of Composed Objects - SelfValidation?

Topics: Validation Application Block
Jul 30, 2009 at 6:01 AM

Hi I have two classes as follows:

    public class Person
    {
        [StringLengthValidator(1, 255, MessageTemplate = "Specify a firstname")]
        public string Firstname { get; set; }

        [StringLengthValidator(1, 255, MessageTemplate = "Specify a lastname")]
        public string Surname { get; set; }

        public ContactInfo ContactDetails { get; set; }
    }

    public class ContactInfo
    {
        [StringLengthValidator(1, 255, MessageTemplate = "Specify a lastname")]
        public string Email { get; set; }

        [StringLengthValidator(1, 255, MessageTemplate = "Specify a lastname")]
        public string PhoneNumber { get; set; }
    }

My problem is that when validating data coming from a webform, Validation.Validate<Person>(person) is returning error messages only for the Person class, however it seems all validators are being fired (Both Person and Contact Info). I tried adding selfvalidation to both but it is not fired in the case of Contact Info. What am i doing wrong?
Thanks in advance,
Jul 30, 2009 at 6:31 AM
Edited Jul 30, 2009 at 6:33 AM

Try adding a[ObjectValidator()] tag on the ContactDetails Property.

public class Person
{
        [StringLengthValidator(1, 255, MessageTemplate = "Specify a firstname")]
        public string Firstname { get; set; }

        [StringLengthValidator(1, 255, MessageTemplate = "Specify a lastname")]
        public string Surname { get; set; }

        [ObjectValidator()]
        public ContactInfo ContactDetails { get; set; }
}
Valiant Dudan
Global Technology and Solutions
Avanade, Inc.
entlib.support@avanade.com

 

Jul 31, 2009 at 4:54 AM

Hi, this does work. Thanks a lot.