MVC Model Range Validator?

2019-01-26 18:27发布

i wnat to validate the datetime, My Code is:

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

but i get the error:

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

please help me?

1条回答
戒情不戒烟
2楼-- · 2019-01-26 18:55

This means the values for the Range attribute can't be determined at some later time, it has to be determined at compile time. DateTime.Now isn't a constant, it changes depending on when the code runs.

What you want is a custom DataAnnotation validator. Here's an example of how to build one:

How to create Custom Data Annotation Validators

Put your date validation logic in IsValid()

Here's an implementation. I also am using DateTime.Subtract() as opposed to negative years.

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

}

Usage is:

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

It's also generic so you can specify new range values for the years.

[DateRange(FirstDateYears = 20, SecondDateYears = 10, ErrorMessage = "Must be between 10 and 20 years ago")]
public DateTime Birthday { get; set; }
查看更多
登录 后发表回答