【问题标题】:Modify default ErrorMessage for StringLength validation修改 StringLength 验证的默认 ErrorMessage
【发布时间】:2012-03-21 08:53:29
【问题描述】:

StringLength 验证的默认 ErrorMessage 比我想要的要长很多:

字段 {Name} 必须是最大长度为 {StringLength} 的字符串。

我想将其普遍更改为:

最大长度为 {StringLength}。

我想避免为我声明的每个字符串重复指定 ErrorMessage:

    [StringLength(20, ErrorMessage="Maximum length is 20")]
    public string OfficePhone { get; set; }
    [StringLength(20, ErrorMessage="Maximum length is 20")]
    public string CellPhone { get; set; }

我很确定我记得有一种简单的方法可以通用地更改 ErrorMessage,但记不起了。

编辑:

为了澄清起见,我正在尝试普遍更改默认的 ErrorMessage 以便我可以输入:

    [StringLength(20)]
    public string OfficePhone { get; set; }

并显示错误消息:

最大长度为 20。

【问题讨论】:

    标签: asp.net-mvc-3 validation entity-framework-4


    【解决方案1】:

    试试

    [ StringLength(20, ErrorMessage = "Maximum length is {1}") ]
    

    如果我没记错的话应该是这样的。

    【讨论】:

    • 并且将错误消息添加到资源文件意味着它只指定一次。
    • @WernerStrydom,请发布关于如何仅指定一次的答案,因为这是我的问题。
    • 是的,我在稍后重读您的问题后注意到了这一点。但看起来您现在得到了您正在寻找的完整答案。
    • @Yarx:你在哪里找到了字符串格式的占位符值?它不在 MSDN 文档中。
    • 我不记得了,但是在查看 StringLengthAttribute 的来源后,您可以在那里找到占位符逻辑。 {0} = 字段名称,{1} = 最大长度,{2} = 最小长度
    【解决方案2】:

    您可以在许多属性上指定 StringLength 属性,如下所示

    [StringLength(20, ErrorMessageResourceName = "StringLengthMessage", ErrorMessageResourceType = typeof(Resource))]
    public string OfficePhone { get; set; }
    [StringLength(20, ErrorMessageResourceName = "StringLengthMessage", ErrorMessageResourceType = typeof(Resource))]
    public string CellPhone { get; set; }
    

    并在资源文件中添加字符串资源(名为StringLengthMessage

    "Maximum length is {1}"
    

    消息被定义一次,并且如果您改变了要测试的长度的想法,它有一个可变的占位符。

    您可以指定以下内容:

    1. {0} - 名称
    2. {1} - 最大长度
    3. {2} - 最小长度

    更新

    为了进一步减少重复,您可以将 StringLengthAttribute 子类化:

    public class MyStringLengthAttribute : StringLengthAttribute
    {
        public MyStringLengthAttribute() : this(20)
        {
        }
    
        public MyStringLengthAttribute(int maximumLength) : base(maximumLength)
        {
            base.ErrorMessageResourceName = "StringLengthMessage";
            base.ErrorMessageResourceType = typeof (Resource);
        }
    }
    

    如果您想添加其他参数,也可以覆盖FormatErrorMessage。现在属性如下所示:

    [MyStringLength]
    public string OfficePhone { get; set; }
    [MyStringLength]
    public string CellPhone { get; set; }
    

    【讨论】:

    • 有没有办法覆盖默认值,而不必为我的架构中的每个用户输入的字符串使用ErrorMessageResourceName = "StringLengthMessage", ErrorMessageResourceType = typeof(Resource))]
    • 没有。但是您可以继承 StringLengthAttribute 并指定默认值。查看我的答案的更新。
    • 我可以指定一个 StrengLength(即[MyStringLength(30)]
    • 根据需要在构造函数中手动设置 MinimumLength。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多