代码之家  ›  专栏  ›  技术社区  ›  Alistair

ASP.NET MVC:添加将DisplayName合并到自定义ValidationAttribute的自定义错误消息

  •  6
  • Alistair  · 技术社区  · 15 年前

    我正在将ASP.NET MVC与DataAnnotations一起使用。我创建了以下自定义的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甚至字段名称。

    有人知道吗?

    1 回复  |  直到 13 年前
        1
  •  9
  •   LukLed    15 年前

    略微修改的StringLength属性:

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