【问题标题】:What parameters does the stringlength attribute errormessage take?stringlength属性errormessage取什么参数?
【发布时间】:2012-11-16 22:23:49
【问题描述】:

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

例如:

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

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

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

我在StringLengthAttribute documentation 中找不到任何相关信息。

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 是的,我想我真正要问的是,除了反复试验,我怎么能知道这一点。它是在FormatErrorMessage 方法中的StringLengthAttribute 类本身中实现的吗?这有记录吗?
    • 如果没有指定MinimumLength 怎么办?如果它是在MaximumLength 为零时设置的唯一属性怎么办?
    • 不知道多年前回答这个问题时是否属实,但文档目前在评论中说明了这一点。 docs.microsoft.com/en-us/dotnet/api/…
    【解决方案2】:

    我也没有看到任何文档,但 StringLengthAttributeFormatErrorMessage 方法看起来像这样:

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

    【讨论】:

      【解决方案3】:

      在我开始获得一些可靠线索之前,比预期更长的 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”对应于“名称”(属性)、“最大长度”和“最小长度”。

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

      【讨论】:

      • 这应该是公认的答案。当前没有解释信息的来源。
      猜你喜欢
      • 2013-08-31
      • 2012-03-21
      • 2020-10-09
      • 1970-01-01
      • 1970-01-01
      • 2016-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多