MVC Model Range Validator?

i wnat to check the date and time, My Code:

[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 an error:

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

Please help me?

+4
source share
1 answer

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); // assuming it in a parsable string format if (date >= DateTime.Now.AddYears(-FirstDateYears)) && date <= DateTime.Now.AddYears(-SecondDateYears))) { return true; } return false; } 

}

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; } 
+11
source

Source: https://habr.com/ru/post/1401747/


All Articles