Kumar
Kumar

Reputation: 2863

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?

Upvotes: 5

Views: 3088

Answers (3)

Sergey Shushert
Sergey Shushert

Reputation: 11

You can override

protected override ValidationResult IsValid(object value, ValidationContext validationContext)

and use validationContext.DisplayName

Upvotes: 1

frezq
frezq

Reputation: 702

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.

Upvotes: 7

marcind
marcind

Reputation: 53181

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") {
}

Upvotes: 3

Related Questions