When I do the following:
`[Range(1910, DateTime.Now.Year)]
public int Year { get; set; }`
I get the following error:
An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
Any ideas why?
You could build for this a custom attribute something like RangeYearToCurrent
in which you specify the current year
public class RangeYearToCurrent : RangeAttribute
{
public RangYearToCurrent(int from)
: base(typeof(int), from, DateTime.Today.Year) { }
}
untested...
Here's my version, based on the previous answer (but working both client/server side):
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class RangeYearToCurrent : RangeAttribute,IClientValidatable {
public RangeYearToCurrent(int from) : base(from, DateTime.Today.Year) { }
#region IClientValidatable Members
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rules = new ModelClientValidationRangeRule(this.ErrorMessage, this.Minimum, this.Maximum);
yield return rules;
}
#endregion
}
Usage Exemple :
[RangeYearToCurrent(1995, ErrorMessage = "Invalid Date")]
public int? Year { get; set; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With