我正在尝试为DateTime编写自定义ValidationAttribute?
但是,当它达到IsValid(object value)
时,该值已经为DateTime.Max
我在代码中看到的任何内容都没有设置此值,但这意味着我正在努力验证它。
我想要的规则是“Null或After Today” - 这意味着如果有Null值则没关系,但如果有值,那么我想验证。
public class AfterTodayAttribute : ValidationAttribute, IClientValidatable
{
public AfterTodayAttribute()
{
}
//Tried this as well...same result
//protected override ValidationResult IsValid(object value, ValidationContext validationContext)
//{
// return base.IsValid(value, validationContext);
//}
public override bool IsValid(object value)
{
//value is already a DateTime and set to DateTime.Max
var valid = false; // for testing only
return valid;
}
}
...
[Display(Description = "Expiry Date")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
[DataType(DataType.Date)]
[AfterToday(false, ErrorMessage = "The Limit Expiry Date must be later than Today")]
public DateTime? NewExpiryDate { get; set; }
...
答案 0 :(得分:1)
这应该可以解决问题:
public override bool IsValid(object value)
{
var dt = value as DateTime?;
return dt == null || dt.Value.Date > DateTime.Today.AddDays(1).AddSeconds(-1);
}
答案 1 :(得分:0)
试试这个:
public override bool IsValid(object value)
{
var dateValue = (DateTime ?) value;
return dateValue.HasValue ? dateValue.Value > DateTime.Now : true;
}