ASP.NET MVC:添加将 DisplayName 合并到自定义 ValidationAttribute 的自定义 ErrorMessage
我正在使用带有 DataAnnotations 的 ASP.NET MVC。我创建了以下自定义 ValidationAttribute ,效果很好。
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 甚至字段名称。
有人知道吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
稍微修改一下 StringLengthAttribute:
slightly modified StringLengthAttribute: