How to get property's display name from a custom attribute
Asked Answered
J

3

5

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?

Jone answered 7/11, 2010 at 0:37 Comment(2)
Are you trying to avoid using the ErrorMessage Property when assigning the attribute? like: MinimumLength(ErrorMessage = "Email Address must be at least 5 characters long")Brucie
Yes I am trying to avoid setting the error message when assigning the attribute.Jone
N
7

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.

Nowt answered 26/7, 2012 at 9:23 Comment(0)
W
3

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") {
}
Warram answered 7/11, 2010 at 1:54 Comment(1)
Ovveriding the FormatErrorMessage method only works on the server side validation but it doesn't work on the client side. So it would be ideal to set the ErrprMessage property.Jone
S
1

You can override

protected override ValidationResult IsValid(object value, ValidationContext validationContext)

and use validationContext.DisplayName

Slyke answered 30/11, 2021 at 14:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.