使用数据注释限制DateTime值

我的模型中有这个DateTime属性:

[Required(ErrorMessage = "Expiration Date is required")] [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)] [DisplayName("Expiration Date")] public DateTime? ExpirationDate { get; set; } 

我希望validation此属性,以便用户无法输入今天之前发生的日期。 如果我validation一个整数,我可以这样做。

 [Range(1, int.MaxValue, ErrorMessage = "Value must be greater than 0")] 

但range属性不支持DateTime对象。 DateTime值有这样的东西吗?

这应该对你有帮助。

 public class MyDateAttribute : ValidationAttribute { public override bool IsValid(object value)// Return a boolean value: true == IsValid, false != IsValid { DateTime d = Convert.ToDateTime(value); return d >= DateTime.Now; //Dates Greater than or equal to today are valid (true) } } 

现在将此属性应用于您的Model属性。

  public class SomeModel { [Display(Name = "Date of birth")] [MyDate(ErrorMessage ="Invalid date")] public DateTime DateOfBirth { get; set; } }