3

我正在尝试为 DateTime 编写自定义 ValidationAttribute?

但是,当它达到IsValid(object value)该值时DateTime.Max

我在代码中看到的任何内容都没有设置此值,但这意味着我正在努力验证它。

我想要的规则是“Null or 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; }
...
4

2 回答 2

1

这应该可以解决问题:

public override bool IsValid(object value)
{
    var dt = value as DateTime?;

    return dt == null || dt.Value.Date > DateTime.Today.AddDays(1).AddSeconds(-1);
}
于 2012-12-09T08:47:24.083 回答
0

尝试这个 :

  public override bool IsValid(object value) 
    {           
        var dateValue = (DateTime ?) value;
        return dateValue.HasValue ? dateValue.Value > DateTime.Now : true;
    }
于 2012-12-09T08:47:48.277 回答