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