C# DateTime 有 RangeAttribute 吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17321948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a RangeAttribute for DateTime?
提问by Flood Gravemind
I have a Datetime field in my Model and need to validate it so that when it is created it has to fall between Nowand 6 Years Prior. I have tried using range like
我的模型中有一个 Datetime 字段,需要对其进行验证,以便它在创建时必须介于Now和6 Years Prior 之间。我试过使用范围
[Range(DateTime.Now.AddYears(-6), DateTime.Now)]
public DateTime Datetim { get; set; }
But this throws an error cannot convert system datetime to double. Can anyone suggest a workaround to this in the model itself?
但这会引发错误,无法将系统日期时间转换为双精度。任何人都可以在模型本身中提出解决方法吗?
采纳答案by Ahmed KRAIEM
Use this attribute:
使用这个属性:
public class CustomDateAttribute : RangeAttribute
{
public CustomDateAttribute()
: base(typeof(DateTime),
DateTime.Now.AddYears(-6).ToShortDateString(),
DateTime.Now.ToShortDateString())
{ }
}
回答by Andrei
Even though there is an overload for Rangeattribute that accepts type and boundary values of that type and allows something like this:
即使Range属性有一个重载,它接受该类型的类型和边界值并允许这样的事情:
[Range(typeof(DateTime), "1/1/2011", "1/1/2012", ErrorMessage="Date is out of Range")]
what you are trying to achieve is not possible using this attribute. The problem is that attributes accept only constants as parameters. Obviously neither DateTime.Nownor DateTime.Now.AddYears(-6)are constants.
使用此属性无法实现您要实现的目标。问题是属性只接受常量作为参数。显然,既不是常数DateTime.Now也不DateTime.Now.AddYears(-6)是常数。
However you can still do this creating your own validation attribute:
但是,您仍然可以创建自己的验证属性:
public class DateTimeRangeAttribute : ValidationAttribute
{
//implementation
}
回答by Sinjai
jQuery validation does not work with RangeAttribute, per Rick Anderson. This renders the selected solution incorrect if you're using ASP.NET MVC 5's built-in jQuery validation.
根据 Rick Anderson 的说法RangeAttribute,jQuery 验证不适用于。如果您使用 ASP.NET MVC 5 的内置 jQuery 验证,这会使所选解决方案不正确。
Instead, see the below code from thisanswer.
相反,请参阅此答案中的以下代码。
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!");
}
}
}
And it's implemented like any other attribute.
它的实现方式与任何其他属性一样。
[WithinSixYears]
public DateTime SixYearDate { get; set; }

