ASP.NET MVC日期时间范围范围、日期、时间、ASP

2023-09-05 03:32:20 作者:心亦冷情亦散

我有日期时间输入字段,我想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;
        }
    }
}
 
精彩推荐
图片推荐