Casey Crookston
Casey Crookston

Reputation: 13955

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

Upvotes: 1

Views: 3757

Answers (2)

David
David

Reputation: 4873

Modified from MSDN.

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class YearRangeAttribute : ValidationAttribute
{
    private int m_min;
    private Range m_range;

    public YearRangeAttribute(int min)
    {
        m_min = min
        m_range = new Range(min, DateTime.Now.Year);
    }


    public override bool IsValid(object value)
    {
        return m_range.IsValid(value)
    }

    public override string FormatErrorMessage(string name)
    {
        return m_range.FormatErrorMessage(name);
    }
}

Disclaimer: This is untested, free-hand code.

Upvotes: 0

lenkan
lenkan

Reputation: 4415

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; }
}

Upvotes: 9

Related Questions