6
我正在使用帶有DataAnnotations的ASP.NET MVC。我創建了以下自定義ValidationAttribute,它可以正常工作。ASP.NET MVC:添加將DisplayName合併到自定義ValidationAttribute的自定義ErrorMessage
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或字段的名稱。
有人知道嗎?
作品!非常感謝你! – Alistair 2010-01-06 23:51:02
偉大 - 雖然我不明白爲什麼需要在構造函數中的回調 – dice 2012-10-18 15:37:29