Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 223
artwl Avatar asked Dec 17 '22 02:12

artwl


1 Answers

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; }
like image 99
mfanto Avatar answered Jan 01 '23 16:01

mfanto