我的模型中有一个Datetime字段,需要对其进行验证,以便在创建时它必须介于Now和6 Years Prior之间.我尝试过使用范围之类的
[Range(DateTime.Now.AddYears(-6), DateTime.Now)]
public DateTime Datetim { get; set; }
Run Code Online (Sandbox Code Playgroud)
但是这会抛出一个错误,无法将系统日期时间转换为双倍.任何人都可以在模型本身中提出解决方法吗?
And*_*rei 29
即使Range
属性有一个重载,它接受该类型的类型和边界值,并允许这样的事情:
[Range(typeof(DateTime), "1/1/2011", "1/1/2012", ErrorMessage="Date is out of Range")]
Run Code Online (Sandbox Code Playgroud)
使用此属性无法实现您要实现的目标.问题是属性只接受常量作为参数.显然既不是DateTime.Now
也不DateTime.Now.AddYears(-6)
是常数.
但是,您仍然可以创建自己的验证属性:
public class DateTimeRangeAttribute : ValidationAttribute
{
//implementation
}
Run Code Online (Sandbox Code Playgroud)
Ahm*_*IEM 27
使用此属性:
public class CustomDateAttribute : RangeAttribute
{
public CustomDateAttribute()
: base(typeof(DateTime),
DateTime.Now.AddYears(-6).ToShortDateString(),
DateTime.Now.ToShortDateString())
{ }
}
Run Code Online (Sandbox Code Playgroud)
根据 Rick Anderson 的RangeAttribute
说法,jQuery 验证不起作用。如果您使用 ASP.NET MVC 5 的内置 jQuery 验证,这会导致所选解决方案不正确。
相反,请参阅此答案中的以下代码。
public class WithinSixYearsAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
value = (DateTime)value;
// This assumes inclusivity, i.e. exactly six years ago is okay
if (DateTime.Now.AddYears(-6).CompareTo(value) <= 0 && DateTime.Now.CompareTo(value) >= 0)
{
return ValidationResult.Success;
}
else
{
return new ValidationResult("Date must be within the last six years!");
}
}
}
Run Code Online (Sandbox Code Playgroud)
它的实现方式与任何其他属性一样。
[WithinSixYears]
public DateTime SixYearDate { get; set; }
Run Code Online (Sandbox Code Playgroud)