【问题标题】:MVC Model Range Validator?MVC 模型范围验证器?
【发布时间】:2012-03-16 06:47:37
【问题描述】:

我想验证日期时间,我的代码是:

    [Range(typeof(DateTime), 
     DateTime.Now.AddYears(-65).ToShortDateString(), 
     DateTime.Now.AddYears(-18).ToShortDateString(),
     ErrorMessage = "Value for {0} must be between {1} and {2}")]
    public DateTime Birthday { get; set; }

但我得到了错误:

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

请帮帮我?

【问题讨论】:

    标签: asp.net-mvc-3 validation date-range code-first


    【解决方案1】:

    这意味着 Range 属性的值不能在以后确定,它必须在编译时确定。 DateTime.Now 不是一个常数,它会根据代码运行的时间而变化。

    您需要的是自定义 DataAnnotation 验证器。以下是如何构建的示例:

    How to create Custom Data Annotation Validators

    将您的日期验证逻辑放入 IsValid()

    这是一个实现。我也使用 DateTime.Subtract() 而不是负年份。

    public class DateRangeAttribute : ValidationAttribute
    {
        public int FirstDateYears { get; set; }
        public int SecondDateYears { get; set; }
    
        public DateRangeAttribute()
        {
            FirstDateYears = 65;
            SecondDateYears = 18;
        }
    
        public override bool IsValid(object value)
        {
            DateTime date = DateTime.Parse(value); // assuming it's in a parsable string format
    
            if (date >= DateTime.Now.AddYears(-FirstDateYears)) && date <= DateTime.Now.AddYears(-SecondDateYears)))
            {
                return true;
            }
    
            return false;
    }
    

    }

    用法是:

    [DateRange(ErrorMessage = "Must be between 18 and 65 years ago")]
    public DateTime Birthday { get; set; }
    

    它也是通用的,因此您可以为年份指定新的范围值。

    [DateRange(FirstDateYears = 20, SecondDateYears = 10, ErrorMessage = "Must be between 10 and 20 years ago")]
    public DateTime Birthday { get; set; }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多