How to get the display name of a property from a user attribute

I am trying to create a minimum length check attribute that will force users to enter a given minimum number of characters in a text box

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 MinimumLengthAttribute constructor, I would like to set the error message as follows:

ErrorMessage = "{0} must be at least {1} characters"

How can I get the display name of a property to populate the {0} placeholder?

+4
source share
2 answers

The placeholder {0} automatically populated with the value for [Display(Name="<value>")] , and if the [Display(Name="")] attribute does not exist, it will accept the name of the property.

+5
source

If your error message contains more than one placeholder, then your attribute should also override the FormatErrorMessage method:

 public override string FormatErrorMessage(string name) { return String.Format(ErrorMessageString, name, MinLength); } 

And you must call one of the constructor overloads to indicate the default error message of your attribute:

 public MinimumLengthAttribute() : base("{0} must be at least {1} characters long") { } 
+2
source

All Articles