c# - 在 DataAnnotations 中使用当前年份作为范围验证

标签 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

最佳答案

您可以创建自己的 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; }
}

关于c# - 在 DataAnnotations 中使用当前年份作为范围验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36228477/

相关文章:

c# - C# 中私有(private)构造函数的需求是什么?

c# - 无法找到请求的.Net Framework 数据提供程序。可能没有安装。(informix)

php - Symfony2 翻译验证消息问题

c# - ErrorMessage with Range 使用数据注释

wcf - WCF 服务契约(Contract)上的数据注释

c# - "..."无法实现接口(interface)成员,因为它不是公共(public)的

c# - Windows Phone 8模拟器调试报错: "a specified communication resource (port) is already in use by another application"

java - 使用一致性配置文件 XML 的 HL7 ADT 消息验证

javascript - 提交前验证表单输入ajax

c# - Web API 验证提供程序是否有枚举属性?