Search code examples
c#validationdata-annotations

Use current year as range validation in DataAnnotations


[Range(1900, DateTime.Now.Year, ErrorMessage = "Please enter a valid year")]

This doesn't work. For "DateTime.Now.Year" it tells me

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

Solution

  • You can create your own RangeUntilCurrentYearAttribute that extends the RangeAttribute.

    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
    public class RangeUntilCurrentYearAttribute : RangeAttribute
    {
        public RangeUntilCurrentYearAttribute(int minimum) : base(minimum, DateTime.Now.Year)
        {
        }
    }
    

    And use it like this:

    public class Foo
    {
        [RangeUntilCurrentYear(1900, ErrorMessage = "Please enter a valid year")]
        public int Year { get; set; }
    }