What parameters does the stringlength attribute errormessage take?

浪子不回头ぞ 提交于 2019-11-28 06:46:10

The {0} index is the display name of property, {1} is the MaximumLength, {2} is the MinimumLength. So, your error message will be formate as "The Foo must be at least 6 characters long."

I haven't seen any documentation either, but the FormatErrorMessage method for the StringLengthAttribute looks like this:

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

A longer-than-expected Google search brought me to this old topic before I could start getting some solid leads, so I'll put this here and hope it helps anyone else in the same shoes:

Inspecting the code for StringLengthAttribute that MS put up on GitHub confirms the logic residing in the FormatErrorMessage method:

// 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);

Thus '0', '1', and '2' corresponds to 'name' (of Property), 'MaximumLength', and 'MinimumLength' accordingly.

I bet the same method can be applied to all other validation attributes to check their formatting parameters accordingly; I was not able to find any other documentation for this infomation otherwise.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!