
We are basically calling a constructor of a class:
The StringLengthAttribute is a class, and its constructor has one int parameter called maximumLength
It also has some Properties:
ErrorMessage of type string
- in our case it's the string:
"The {0} must be at least {2} characters long."
ErrorMessageResourceName of type string
- in our case we don't give it any value
ErrorMessageResourceType of type System.Type
- in our case we don't give it any value
MinimumLength of type int
- in our case we give it the value
6
the ErrorMessageResourceName string has nothing to do (yet) with the other properties, so it is nothing like this:
String.Format("some variable {0} and some other {1}...", 100, 6)
so the number 100 and the property MinimumLength = 6 are not at all (yet) parameters sent to be formatted with the string "The {0} must be at least {2} characters long.".
The class StringLengthAttribute also has some methods, one of them is called FormatErrorMessage
This method is called internally to format the message, and it internally formats the string using String.Format, and here is when the parameters are passed to the string to be correctly formatted.
- {0} is bound to DisplayName
- {1} is bound to MaximumLength
- {2} is bound to MinimumLength
this is the method that is called internally (if you want to know how it internally does it):
/// <summary>
/// Override of <see cref="ValidationAttribute.FormatErrorMessage"/>
/// </summary>
/// <param name="name">The name to include in the formatted string</param>
/// <returns>A localized string to describe the maximum acceptable length</returns>
/// <exception cref="InvalidOperationException"> is thrown if the current attribute is ill-formed.</exception>
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);
}
References:
- Microsoft Reference Source here
- A similar question on Stackoverflow: "What parameters does the stringlength attribute errormessage take?" here
- The almost useless msdn documentation for
StringLengthAttribute Class here