我有日期时间输入字段,我想ASURE用户输入一个日期ATLEAST 24小时后比Datetime.Now。我想这样的:
I am having a datetime input field and I want to asure user enters a date atleast 24 hours later than Datetime.Now. I tried this:
[Range(typeof(DateTime), DateTime.Now.ToString(), DateTime.Now.AddDays(1).ToString())]
public DateTime EndDate { get; set; }
不过,我收到编译器错误,因为值必须是一个常量。所以,我应该怎么办?
But I am getting compiler error because values must be a constants. So what should I do?
你需要的是一个自定义的验证属性,以便你可以做你的比较:
What you need is a custom validation attribute so that you can do your comparison:
[CustomValidation(typeof (Validator), "ValidateEndTimeRange")]
public DateTime EndDate { get; set; }
然后你的实际验证:
And then your actual validator:
namespace MyMVCApp
{
public class Validator
{
public static ValidationResult ValidateEndTimeRange(DateTime endTime)
{
if(endTime.EndDate < DateTime.Now || endTime.EndDate > DateTime.Now.AddDays(1)){
return new ValidationResult("Your end date is outside of the acceptable range.");
}
return ValidationResult.Success;
}
}
}