【问题标题】:Is there a RangeAttribute for DateTime?DateTime 有 RangeAttribute 吗?
【发布时间】:2013-06-26 13:49:30
【问题描述】:

我的模型中有一个日期时间字段,需要对其进行验证,以便在创建它时它必须介于 现在6 年前 之间。我尝试过使用像

这样的范围
[Range(DateTime.Now.AddYears(-6), DateTime.Now)]
public DateTime Datetim { get; set; }

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

【问题讨论】:

  • 对于使用 ASP MVC 的任何人,尝试使用 RangeAttribute 进行客户端验证以进行日期时间验证,您可能希望看到此 article
  • asp.net webapi 呢?

标签: c# asp.net-mvc


【解决方案1】:

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

[Range(typeof(DateTime), "1/1/2011", "1/1/2012", ErrorMessage="Date is out of Range")]

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

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

public class DateTimeRangeAttribute : ValidationAttribute
{
    //implementation
}

【讨论】:

  • Range 的这种使用,即使在您的示例中正常使用,也不起作用。即使值在范围内,它也总是无效
  • 对我来说效果很好
  • 我也是!最佳答案!
  • @toddmo 和其他求职者。 github.com/dotnet/aspnetcore/issues/…如果我理解正确的话,客户端验证还没有完成。
【解决方案2】:

使用这个属性:

public class CustomDateAttribute : RangeAttribute
{
  public CustomDateAttribute()
    : base(typeof(DateTime), 
            DateTime.Now.AddYears(-6).ToShortDateString(),
            DateTime.Now.ToShortDateString()) 
  { } 
}

【讨论】:

  • 为了得到更漂亮的验证信息 FormatErrorMessage 方法应该被覆盖
  • 我知道这是旧的,但你如何在模型中使用它?
  • 您将其添加为属性(使用上面的代码,您只需在属性上方键入 [CustomDate])。
  • 请注意,ToShortDateString() 仅包括 DateTime 的 Date 部分,如果您要验证到现在(第二个),toString 可能会更好。但还要注意,这根本不考虑本地时间与 UTC 时间,因为它会与 ToString 的输出进行比较,从而剥离它是本地时间还是 UTC。
【解决方案3】:

jQuery 验证不适用于RangeAttributeper Rick Anderson。如果您使用 ASP.NET MVC 5 的内置 jQuery 验证,这会导致所选解决方案不正确。

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

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!");
        }
    }
}

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

[WithinSixYears]
public DateTime SixYearDate { get; set; }

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2011-07-19
  • 1970-01-01
  • 2010-11-13
  • 1970-01-01
  • 2012-04-24
  • 1970-01-01
  • 2018-08-03
  • 2015-01-01
相关资源
最近更新 更多