Question

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?

Was it helpful?

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."

OTHER TIPS

You can try something like this:

public class Person
{
    public DateTime BirthDate { get; set; }

    [RangeValidator(0, RangeBoundaryType.Inclusive, 150, RangeBoundaryType.Exclusive,
        MessageTemplate="Person must be less than 150 years old.")]
    public int Age
    {
        get { return (DateTime.Now - this.BirthDate).Days / 365; }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top