使用当前年份作为DataAnnotations中的范围验证

时间:2016-03-25 21:39:09

标签: c# validation data-annotations

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

这不起作用。对于" DateTime.Now.Year"它告诉我

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

2 个答案:

答案 0 :(得分:3)

您可以创建自己的 RangeUntilCurrentYearAttribute ,扩展 RangeAttribute

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

并像这样使用它:

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

答案 1 :(得分:0)

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

免责声明:这是未经测试的免费代码。