开发者

ASP.NET MVC: Adding custom ErrorMessage that incorporates DisplayName to custom ValidationAttribute

I am using ASP.NET MVC with DataAnnotations. I have created the following custom ValidationAttribute which works fine.

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

However, the error message that appears is the standard "The field * is invalid". I would like to change this to be: "The [DisplayName] must be betw开发者_如何学Goeen [minlength] and [maxlength]", however I cannot figure out how to get the DisplayName or even the name of the field from inside this class.

Anyone know?


slightly modified 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; }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜