asp.net-mvc-3 – MVC模型范围验证器?

前端之家收集整理的这篇文章主要介绍了asp.net-mvc-3 – MVC模型范围验证器?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想验证日期时间,我的代码是:
[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

请帮帮我?

解决方法

这意味着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; }

猜你在找的asp.Net相关文章