This means that the values ββof the Range attribute cannot be determined later; this must be determined at compile time. DateTime.Now is not a constant, it changes depending on when the code is executed.
What you want is a custom DataAnnotation validator. Here is an example of how to build it:
How to create custom data annotation checks
Put date validation logic in IsValid ()
Here is the implementation. I also use 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);
}
Using:
[DateRange(ErrorMessage = "Must be between 18 and 65 years ago")] public DateTime Birthday { get; set; }
It is also general, so you can specify new range values ββover the years.
[DateRange(FirstDateYears = 20, SecondDateYears = 10, ErrorMessage = "Must be between 10 and 20 years ago")] public DateTime Birthday { get; set; }
source share