1

I am trying to validate a year field in my model for a credit card. I want to grab the current year as the minimum value. Here is my code:

[Required]
[Range(DateTime.Now.Year, DateTime.Now.Year+20, ErrorMessage="Please enter a valid year")] 
[Display(Name = "Exp. Year")]
public int expYear { get; set; }

The error I am getting is: "An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type" on the "DateTime.Now.Year" code.

Sparky
  • 98,165
  • 25
  • 199
  • 285
dmikester1
  • 1,374
  • 11
  • 55
  • 113
  • The exception message is fairly explicitly. What specifically don't you understand about it? – Daniel Kelley May 06 '14 at 16:19
  • 2
    you can make a knockoff of [this answer](http://stackoverflow.com/questions/17321948/is-there-a-range-attribute-for-datetime), it's almost a duplicate – Jonesopolis May 06 '14 at 16:19
  • 1
    @Jonesy That answer would not be much better than hard-coding the current year. The constructor of `RangeAttribute` is still only called once, so the years never update. The proper solution is to define a method that checks `DateTime.Now.Year` on every validation, e.g. through [CustomValidationAttribute](http://weblogs.asp.net/peterblum/archive/2009/12/07/the-customvalidationattribute.aspx). – nmclean May 06 '14 at 17:33

1 Answers1

0

DateTime.Now.Year is not a constant that can be compiled into the assembly and that is where the attributes go.

Konsole
  • 3,447
  • 3
  • 29
  • 39
  • Well, I can't hard code 2014 in because next year that will change. – dmikester1 May 06 '14 at 17:03
  • 1
    Check this post [link](http://stackoverflow.com/questions/2720735/asp-mvc-custom-validation-attribute). You may need to write a custom attribute and use a bit of reflection to fetch the limits. You can pass some constant string(s) to give your attribute idea where to obtain the required value or may by in your specific case you can do it just by using DateTime.Now inside your IsValid method in that attribute. – MichaelElfial May 06 '14 at 17:24