Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
885 views
in Technique[技术] by (71.8m points)

asp.net mvc 3 - MVC Model Range Validator?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...