stringlength属性errormessage采用什么参数?

时间:2012-11-16 22:23:49

标签: c# asp.net-mvc-4 data-annotations

在MVC4模板中,使用的数据注释属性之一是stringlength。

例如:

[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]

哪些参数{0},{1},{2}(更多?)是合法的?

编辑:更具体地说,我可以从示例和反复试验中看到可能性是什么,但我希望看到一些硬文档。

我在StringLengthAttribute documentation中找不到任何相关内容。

3 个答案:

答案 0 :(得分:45)

{0}索引是属性的显示名称,{1}MaximumLength{2}MinimumLength。因此,您的错误消息将合成为"The Foo must be at least 6 characters long."

答案 1 :(得分:12)

我也没有看到任何文档,但FormatErrorMessage的{​​{1}}方法如下所示:

StringLengthAttribute

答案 2 :(得分:2)

一个比预期更长的Google搜索使我进入了这个老话题,然后我才开始获得扎实的潜在客户,因此我将其放在这里,希望对其他人有帮助。

检查MS在GitHub上放置的StringLengthAttribute的代码,以确认FormatErrorMessage方法中存在的逻辑:

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

因此,“ 0”,“ 1”和“ 2”对应于“属性的名称”,“ MaximumLength”和“ MinimumLength”。

我敢肯定,可以将相同的方法应用于所有其他验证属性,以相应地检查其格式参数;否则,我无法找到此信息的任何其他文档。

相关问题