Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 between [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?

like image 732
Alistair Avatar asked Jan 06 '10 00:01

Alistair


1 Answers

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; }
}
like image 187
LukLed Avatar answered Oct 22 '22 20:10

LukLed