Question

When create new MVC5 application, there is a ViewModel with this property:

[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; }

I'm interesting in this part:

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

I believe that {0} gets string from [Display(Name = "New password")] and {2} gets string from MinimumLength = 6.

What I don't understand, is why they are in this particular order? I mean why exactly {2} and not, say, {1} gets value from MinimumLength = 6? The same question for {0}. How can I determine this order?

Is next declaration would be correct? I expect that {0} gets display name and {1} - length: 25.

[MinLength(length: 25, ErrorMessage = "Length of {0} must be at least {1} characters long.")]
[Display(Name = "My property")]
public string MyProperty { get; set; }

What would be if I remove attribute [Display(Name = "My property")]? Does {0} in that case just takes name of my property "MyProperty"?

Thanks.

Was it helpful?

Solution

"What is why they are in this particular order?"

The order is:

  1. Display Name
  2. MaximumLength
  3. MinimumLength

The answer on question string frormat is in FormatErrorMessage method of StringLengthAttribute.cs:

public override string FormatErrorMessage(string name) {
    this.EnsureLegalLengths();

    bool useErrorMessageWithMinimum = this.MinimumLength != 0 && !this.CustomErrorMessageSet;

    string errorMessage = useErrorMessageWithMinimum ?
        DataAnnotationsResources.StringLengthAttribute_ValidationErrorIncludingMinimum : this.ErrorMessageString;

    // it's ok to pass in the minLength even for the error message without a {2} param since String.Format will just
    // ignore extra arguments
    return String.Format(CultureInfo.CurrentCulture, errorMessage, name, this.MaximumLength, this.MinimumLength);
}

"What would be if I remove attribute [Display(Name = "My property")]? Does {0} in that case just takes name of my property "MyProperty":

Yes it would use member name.

Here is a code of DisplayName property which is passed as name to FormatErrorMessage:

public string DisplayName {
    get {
        if (string.IsNullOrEmpty(this._displayName)) {
            this._displayName = this.GetDisplayName();

            if (string.IsNullOrEmpty(this._displayName)) {
                this._displayName = this.MemberName;

                if (string.IsNullOrEmpty(this._displayName)) {
                    this._displayName = this.ObjectType.Name;
                }
            }
        }
        return this._displayName;
    }   
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top