Pregunta

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?

¿Fue útil?

Solución

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

Otros consejos

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; }
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top