How to get property's display name from a custom attribute
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?
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.
If your error message has more than one placeholder, they your attribute should also override the FormatErrorMessage method like so:
public override string FormatErrorMessage(string name) {
return String.Format(ErrorMessageString, name, MinLength);
}
And you should call one of the constructor overloads to specfiy your attribute's default error message:
public MinimumLengthAttribute()
: base("{0} must be at least {1} characters long") {
}
You can override
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
and use validationContext.DisplayName
精彩评论