Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 344
Kumar Avatar asked Nov 07 '10 00:11

Kumar


1 Answers

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.

like image 58
frezq Avatar answered Sep 16 '22 19:09

frezq