使用数据注释限制DateTime值

Ste*_*ven 15 c# asp.net asp.net-mvc asp.net-mvc-3

我的模型中有这个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; }
Run Code Online (Sandbox Code Playgroud)

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

[Range(1, int.MaxValue, ErrorMessage = "Value must be greater than 0")]
Run Code Online (Sandbox Code Playgroud)

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

Par*_*der 37

这应该对你有帮助.

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)

    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

  • 您可以使用[MyDate(ErrorMessage ="您的消息在这里")] (2认同)