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?