如何从自定义属性获取属性的显示名称
我正在尝试创建一个最小长度验证属性,该属性将强制用户在文本框中输入指定的最小数量的字符
public sealed class MinimumLengthAttribute : ValidationAttribute
{
public int MinLength { get; set; }
public MinimumLengthAttribute(int minLength)
{
MinLength = minLength;
}
public override bool IsValid(object value)
{
if (value == null)
{
return true;
}
string valueAsString = value as string;
return (valueAsString != null && valueAsString.Length >= MinLength);
}
}
在 MaximumLengthAttribute 的构造函数中,我想将错误消息设置如下:
ErrorMessage =“{0} 必须是至少 {1} 个字符长”
如何获取属性的显示名称以便填充 {0} 占位符?
I am trying to create a minimum length validation attribute which will force users to enter the specified minimum amount of characters into a textbox
public sealed class MinimumLengthAttribute : ValidationAttribute
{
public int MinLength { get; set; }
public MinimumLengthAttribute(int minLength)
{
MinLength = minLength;
}
public override bool IsValid(object value)
{
if (value == null)
{
return true;
}
string valueAsString = value as string;
return (valueAsString != null && valueAsString.Length >= MinLength);
}
}
In the constructor of the MinimumLengthAttribute I would like to set the error message as follows:
ErrorMessage = "{0} must be atleast {1} characters long"
How can I get the property's display name so that I can populate the {0} placeholder?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以覆盖
并使用
validationContext.DisplayName
You can override
and use
validationContext.DisplayName
{0}
占位符会自动填充[Display(Name="")]
的值,并且如果[Display(Name= "")]
属性不存在,那么它将采用属性的名称。The
{0}
placeholder is automatically populated with the value for[Display(Name="<value>")]
and if the[Display(Name="")]
attribute doesn't exist then It will take the Name of the property.如果您的错误消息有多个占位符,则您的属性还应覆盖 FormatErrorMessage 方法如下:
您应该调用构造函数重载之一来指定属性的默认错误消息:
If your error message has more than one placeholder, they your attribute should also override the FormatErrorMessage method like so:
And you should call one of the constructor overloads to specfiy your attribute's default error message: