validationenterprise-libraryvalidation-application-bl

Validate age by date of birth using Enterprise Library Validation Application Block


I have the following situation: A domain model that has a property BithDay. I want to be able to verify that the age (that will be computed accordingally to the birthday) is lower than 150 years. Can I do that by using the built in validtors or I have to build my own? Can someoane provide me an example of DomainValidator?


Solution

  • You can use a RelativeDateTimeValidator to validate an age based on a Birth Date. For example:

    public class Person
    {
        [RelativeDateTimeValidator(-150, DateTimeUnit.Year, RangeBoundaryType.Inclusive, 
            0, DateTimeUnit.Year, RangeBoundaryType.Ignore,
            MessageTemplate="Person must be less than 150 years old.")]
        public DateTime BirthDate
        {
            get;
            set;
        }
    }
    
    // 150 Year old person
    Person p = new Person() { BirthDate = DateTime.Now.AddYears(-150) };
    
    var validator = ValidationFactory.CreateValidator<Person>();
    ValidationResults vrs = validator.Validate(p);
    
    foreach (ValidationResult vr in vrs)
    {
        Console.WriteLine(vr.Message);
    }
    

    This will print: "Person must be less than 150 years old."