c# - 使用数据注释限制 DateTime 值

标签 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; }

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

[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)

    }
}

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

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

关于c# - 使用数据注释限制 DateTime 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8844747/

相关文章:

c# - 通过 PowerShell 调用 user32.dll "SetWindowCompositionAttribute"

c# - 编写我们自己的 Dispose 方法而不是使用 Idisposable

asp.net - 通过域名限制对网站的访问

c# - ITextSharp - 将两个 pdf 合并到一个页面中

c# - 如何延长http响应的时间长度

c# - 如何让 asp.net mvc 复选框触发一个 Action ?

c# - 使用 C# 的正则表达式

c# - 创建一个 PerfMon 计数器来记录每次调用的平均值 (C#)

c# - 如何在 ASP.NET 中创建无 key URL 参数

javascript - 如何将数据从ajax javascript传递到MVC Controller ?