ASP.NET MVC: Adicionando ErrorMessage personalizado que incorpora DisplayName ao ValidationAttribute personalizado
Eu estou usando o asp.net MVC com DataAnnotations. Eu criei o seguinte ValidationAttribute personalizado que funciona bem.
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);
}
}
No entanto, a mensagem de erro exibida é o padrão "O campo * é inválido". Eu gostaria de mudar isso para ser: "O [DisplayName] deve ser entre [minlength] e [maxlength]", no entanto eu não consigo descobrir como obter o DisplayName ou até mesmo o nome do campo de dentro desta classe.
Ninguem sabe?