MVC中日期时间和日期字段的范围限制

时间:2016-11-11 07:54:07

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

我正在使用System.Data.SqlTypes.SqlDateTime.MinValueSystem.Data.SqlTypes.SqlDateTime.MaxValue使用以下代码行来定义Datetime和Date字段的范围。

[Range(typeof(DateTime), "1/1/1753 12:00:00 AM", "12/31/9999 11:59:59 PM", ErrorMessage="\'D2\' must be within 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.")]
public System.Nullable<System.DateTime> D2{get;set;}//;

但是当我在文本框中输入日期11/08/2016 12:00 am时,它会抛出错误消息

  

&#39; D2&#39;必须在1/1/1753 12:00 AM和12/31/9999 11:59 PM之内。

所以请告诉我上面的代码有什么问题。

1 个答案:

答案 0 :(得分:0)

您可以为您的班级使用IValidatableObject界面,并检查日期验证,如下所示

public class Sample : IValidatableObject
{
    public DateTime Date { set; get; }
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (Date > new DateTime(2012, 12, 12))
        {
            yield return new ValidationResult("you cant enter it");
        }
    }
}