我想验证日期时间,我的代码是:
[Range(typeof(DateTime),
DateTime.Now.AddYears(-65).ToShortDateString(),
DateTime.Now.AddYears(-18).ToShortDateString(),
ErrorMessage = "Value for {0} must be between {1} and {2}")]
public DateTime Birthday { get; set; }
但我得到错误:
An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
请帮帮我?
答案 0 :(得分:12)
这意味着Range属性的值无法在以后确定,必须在编译时确定。 DateTime.Now不是常量,它会根据代码运行的时间而变化。
您想要的是自定义DataAnnotation验证器。以下是如何构建一个的示例:
How to create Custom Data Annotation Validators
将您的日期验证逻辑放入IsValid()
这是一个实现。我也使用DateTime.Subtract()而不是负数年。
public class DateRangeAttribute : ValidationAttribute
{
public int FirstDateYears { get; set; }
public int SecondDateYears { get; set; }
public DateRangeAttribute()
{
FirstDateYears = 65;
SecondDateYears = 18;
}
public override bool IsValid(object value)
{
DateTime date = DateTime.Parse(value); // assuming it's in a parsable string format
if (date >= DateTime.Now.AddYears(-FirstDateYears)) && date <= DateTime.Now.AddYears(-SecondDateYears)))
{
return true;
}
return false;
}
}
用法是:
[DateRange(ErrorMessage = "Must be between 18 and 65 years ago")]
public DateTime Birthday { get; set; }
它也是通用的,因此您可以指定多年的新范围值。
[DateRange(FirstDateYears = 20, SecondDateYears = 10, ErrorMessage = "Must be between 10 and 20 years ago")]
public DateTime Birthday { get; set; }