I have created the following custom ValidationAttribute:
public class DateRangeAttribute : ValidationAttribute, IClientValidatable {
public DateTime MinimumDate = new DateTime(1901, 1, 1);
public DateTime MaximumDate = new DateTime(2099, 12, 31);
public DateRangeAttribute(string minDate, string maxDate, string errorMessage) {
MinimumDate = DateTime.Parse(minDate);
MaximumDate = DateTime.Parse(maxDate);
ErrorMessage = string.Format(errorMessage, MinimumDate.ToString("MM/dd/yyyy"), MaximumDate.ToString("MM/dd/yyyy"));
}
}
that I would like to use in my MVC4 view model as follows:
[DateRange(Resources.MinimumDate, Resources.MaximumDate, "Please enter a date between {0} and {1}")]
Resources is a generated resources class based on a set of options stored in a SQL database. A simplified version of the generated code for the above two resource properties is:
public class Resources {
public const string MinimumDate = "PropMinimumDate";
public static string PropMinimumDate
{
get { return "12/15/2010" }
}
public const string MaximumDate = "PropMaximumDate";
public static string PropMaximumDate
{
get { return "12/15/2012" }
}
}
While I do not understand how it works, I do understand that typical usage of resources in ValidationAttributes will automatically map Resources.MinimumDate to PropMinimumDate and return the value “12/15/2010”.
What I am cannot figure out is how to manually make that programmatic leap myself so I can pass in the two date values into my custom ValidatorAttribute. As presently coded, “PropMinimumDate” and “PropMaximumDate” are the minDate and maxDate parameter values (respectively) passed into the constructor of the DateRangeAttribute.
If I try
[DateRange(Resources.PropMinimumDate, Resources.PropMaximumDate, "Please enter a date between {0} and {1}")]
I receive the compile error:
An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
Is there a way to accomplish this task, or am I attempting the impossible?
You need to take the
Typeof the resource class as an argument and then use reflections to get the property value.Eg