This question already has answers here:
Is there a RangeAttribute for DateTime?
                                
                                    (3个答案)
                                
                        
                                5年前关闭。
            
                    
我有一个日期时间输入字段,我想确保用户输入的日期至少比日期时间晚24小时。我尝试了这个:

    [Range(typeof(DateTime), DateTime.Now.ToString(), DateTime.Now.AddDays(1).ToString())]
    public DateTime EndDate { get; set; }


但是我遇到编译器错误,因为值必须是常量。所以我该怎么做?

最佳答案

您需要一个自定义验证属性,以便您可以进行比较:

[CustomValidation(typeof (Validator), "ValidateEndTimeRange")]
public DateTime EndDate { get; set; }


然后是您的实际验证器:

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;
        }
    }
}

10-05 21:04
查看更多