【问题标题】:Restrict DateTime value with data annotations使用数据注释限制 DateTime 值
【发布时间】:2012-01-13 01:21:12
【问题描述】:

我的模型中有这个 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 值是否存在类似情况?

【问题讨论】:

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


【解决方案1】:

这应该对您有所帮助。

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

【讨论】:

  • 您可以用作 [MyDate(ErrorMessage ="Your message here")]
猜你喜欢
  • 1970-01-01
  • 2011-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多