Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substitution arguments in ValidationAttribute.ErrorMessage

In an ASP.NET MVC 4 app, the LocalPasswordModel class (in Models\AccountModels.cs) looks like this:

public class LocalPasswordModel
{
    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Current password")]
    public string OldPassword { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "New password")]
    public string NewPassword { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm new password")]
    [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }
}

The above code contains two substitution arguments in the ErrorMessage string:

ErrorMessage = "The {0} must be at least {2} characters long."

Can someone tell me where the values that get substituted into that string come from? More generally, is there anything approximating official documentation that describes how parameter substitution works in this context?

like image 305
Bob.at.Indigo.Health Avatar asked Mar 04 '13 01:03

Bob.at.Indigo.Health


1 Answers

For StringLengthAttribute, the message string can take 3 arguments:

{0} Property name
{1} Maximum length
{2} Minimum length

These parameters unfortunately do not seem to be well documented. The values are passed in from each validation attribute's FormatErrorMessage attribute. For example, using .NET Reflector, here is that method from StringLengthAttribute:

public override string FormatErrorMessage(string name)
{
    EnsureLegalLengths();
    string format = ((this.MinimumLength != 0) && !base.CustomErrorMessageSet) ? DataAnnotationsResources.StringLengthAttribute_ValidationErrorIncludingMinimum : base.ErrorMessageString;
    return String.Format(CultureInfo.CurrentCulture, format, new object[] { name, MaximumLength, MinimumLength });
}

It is safe to assume that this will never change because that would break just about every app that uses it.

like image 156
Eilon Avatar answered Nov 12 '22 17:11

Eilon