【问题标题】:ASP.NET MVC: Adding custom ErrorMessage that incorporates DisplayName to custom ValidationAttributeASP.NET MVC:添加将 DisplayName 合并到自定义 ValidationAttribute 的自定义 ErrorMessage
【发布时间】:2010-01-06 00:19:03
【问题描述】:

我正在使用带有 DataAnnotations 的 ASP.NET MVC。我创建了以下自定义 ValidationAttribute,它工作正常。

public class StringRangeAttribute : ValidationAttribute
{
    public int MinLength { get; set; }
    public int MaxLength { get; set; }

    public StringRangeAttribute(int minLength, int maxLength)
    {   
        this.MinLength = (minLength < 0) ? 0 : minLength;
        this.MaxLength = (maxLength < 0) ? 0 : maxLength;
    }

    public override bool IsValid(object value)
    {            
        //null or empty is <em>not</em> invalid
        string str = (string)value;
        if (string.IsNullOrEmpty(str))
            return true;

        return (str.Length >= this.MinLength && str.Length <= this.MaxLength);
    }
}

但是,出现的错误消息是标准的“字段 * 无效”。我想将其更改为:“[DisplayName] 必须介于 [minlength] 和 [maxlength] 之间”,但是我无法弄清楚如何从此类中获取 DisplayName 甚至字段的名称。

有人知道吗?

【问题讨论】:

    标签: asp.net-mvc data-annotations


    【解决方案1】:

    稍微修改了StringLengthAttribute:

    public class StringRangeAttribute : ValidationAttribute
    {
        // Methods
        public StringRangeAttribute(int minimumLength, int maximumLength)
            : base(() => "The {0} must be between {1} and {2} chars long.")
        {
            MaximumLength = maximumLength;
            MinimumLength = minimumLength;
        }
    
        public override string FormatErrorMessage(string name)
        {
            return string.Format(CultureInfo.CurrentCulture, ErrorMessageString, new object[] { name, MinimumLength ,MaximumLength });
        }
    
        public override bool IsValid(object value)
        {
            if (value != null)
            {
                return (((string)value).Length <= MaximumLength) && (((string)value).Length >= MinimumLength);
            }
            return true;
        }
    
        public int MaximumLength { get; set; }
        public int MinimumLength { get; set; }
    }
    

    【讨论】:

    • 很好 - 虽然我不明白为什么需要构造函数中的回调
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    相关资源
    最近更新 更多