DateTime是否有RangeAttribute?

Flo*_*ind 22 c# asp.net-mvc

我的模型中有一个Datetime字段,需要对其进行验证,以便在创建时它必须介于Now6 Years Prior之间.我尝试过使用范围之类的

[Range(DateTime.Now.AddYears(-6), DateTime.Now)]
public DateTime Datetim { get; set; }
Run Code Online (Sandbox Code Playgroud)

但是这会抛出一个错误,无法将系统日期时间转换为双倍.任何人都可以在模型本身中提出解决方法吗?

And*_*rei 29

即使Range属性有一个重载,它接受该类型的类型和边界值,并允许这样的事情:

[Range(typeof(DateTime), "1/1/2011", "1/1/2012", ErrorMessage="Date is out of Range")]
Run Code Online (Sandbox Code Playgroud)

使用此属性无法实现您要实现的目标.问题是属性只接受常量作为参数.显然既不是DateTime.Now也不DateTime.Now.AddYears(-6)是常数.

但是,您仍然可以创建自己的验证属性:

public class DateTimeRangeAttribute : ValidationAttribute
{
    //implementation
}
Run Code Online (Sandbox Code Playgroud)

  • 这种“范围”的使用,即使在作为您的示例的正常使用情况下,也不起作用。即使值在范围内,它也总是无效 (2认同)

Ahm*_*IEM 27

使用此属性:

public class CustomDateAttribute : RangeAttribute
{
  public CustomDateAttribute()
    : base(typeof(DateTime), 
            DateTime.Now.AddYears(-6).ToShortDateString(),
            DateTime.Now.ToShortDateString()) 
  { } 
}
Run Code Online (Sandbox Code Playgroud)

  • 要获得更漂亮的验证消息,应覆盖FormatErrorMessage方法 (2认同)
  • 我知道这很旧,但是你如何在模型中使用它? (2认同)

Sin*_*jai 5

根据 Rick Anderson 的RangeAttribute说法,jQuery 验证不起作用。如果您使用 ASP.NET MVC 5 的内置 jQuery 验证,这会导致所选解决方案不正确。

相反,请参阅此答案中的以下代码。

public class WithinSixYearsAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        value = (DateTime)value;
        // This assumes inclusivity, i.e. exactly six years ago is okay
        if (DateTime.Now.AddYears(-6).CompareTo(value) <= 0 && DateTime.Now.CompareTo(value) >= 0)
        {
            return ValidationResult.Success;
        }
        else
        {
            return new ValidationResult("Date must be within the last six years!");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

它的实现方式与任何其他属性一样。

[WithinSixYears]
public DateTime SixYearDate { get; set; }
Run Code Online (Sandbox Code Playgroud)

  • jQuery 验证可以轻松扩展以支持日期范围。请参阅/sf/answers/2942563851/ (2认同)