1

我有以下情况:具有属性 BithDay 的域模型。我希望能够验证年龄(将根据生日计算)低于 150 岁。我可以通过使用内置验证器来做到这一点,还是必须自己构建?someoane 可以为我提供 DomainValidator 的示例吗?

4

2 回答 2

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

于 2013-10-23T19:03:35.853 回答
1

你可以尝试这样的事情:

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; }
    }
}
于 2013-10-24T09:53:10.387 回答