DateTime的MVC3 ValidationAttribute?在IsValid(...)中返回DateTime.Max

时间:2012-12-09 08:37:06

标签: c# asp.net-mvc-3 validationattribute

我正在尝试为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; }
...

2 个答案:

答案 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;
    }