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?
Asked
Active
Viewed 344 times
2 Answers
1
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."

Randy Levy
- 22,566
- 4
- 68
- 94
-
Is there a way to use this tipe of validation relative to another property in object? – MariaMadalina Oct 24 '13 at 09:44
-
How can I add complex validation between objects? In this case I have to compute the age at the time when the person details were added in the database.Therefore I have another property of another object (the Person's parent in the hierarchy) that stores data regarding the date the object was added? Is there a way to compute age based on that value? – MariaMadalina Oct 24 '13 at 09:49
1
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; }
}
}

Steven
- 166,672
- 24
- 332
- 435