【发布时间】:2015-06-08 23:51:25
【问题描述】:
我创建了一个自定义 ValidationAttribute 类来检查我的应用程序中的人的年龄:
public class MinimumAgeAttribute : ValidationAttribute
{
public int MinAge { get; set; }
public override bool IsValid(object value)
{
return CalculateAge((DateTime) value) >= MinAge;
}
private int CalculateAge(DateTime dateofBirth)
{
DateTime today = DateTime.Now;
int age = today.Year - dateofBirth.Year;
if (dateofBirth > today.AddYears(-age)) age--;
return age;
}
}
在字段上设置数据注释是这样的:
[MinimumAge(MinAge = 18, ErrorMessage = "Person must be over the age of 18")]
public DateTime DateOfBirth;
我的 UI 中的绑定设置如下:
<DatePicker SelectedDate="{Binding SelectedPerson.DateOfBirth, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" Grid.Column="1"/>
例如,当我将日期(例如)设置为 09/06/2007 时,Validator.TryValidateObject 总是返回 true。
为什么?这似乎只会影响我的自定义类,System.ComponentModel.DataAnnotations 中提供的所有类都可以正常工作。
【问题讨论】:
-
不确定这是否能解决您的问题,但在处理日期时,请始终考虑您转换的文化。你有一个从
object到DateTime的直接转换。 -
你有没有通过你的代码来查看变量的值是什么?
CalculateAge为您的示例日期返回什么? -
也许这个答案可能会有所帮助:stackoverflow.com/questions/29665290/…
-
@Ron CalculateAge 永远不会被调用。
-
从上面显示的代码中,我假设您正在使用 WPF。这是正确的吗?
标签: c# data-annotations