【问题标题】:DataAnnotations StringLength Attribute MVC - without max valueDataAnnotations StringLength 属性 MVC - 没有最大值
【发布时间】:2012-07-09 09:48:06
【问题描述】:

我在 MVC4 中使用数据注释进行模型验证,目前正在使用 StringLengthAttribute,但我不想指定最大值(当前设置为 50),但我想指定最小字符串长度值。

有没有办法只指定最小长度?也许我可以使用另一个属性?

我当前的代码是:

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Confirm New Password")]
    [StringLength(50, MinimumLength = 7)]
    [CompareAttribute("NewPassword", ErrorMessage = "The New Password and Confirm New Password fields did not match.")]
    public string ConfirmNewPassword { get; set; }

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4 data-annotations minimum string-length


    【解决方案1】:

    有没有办法只指定最小长度?也许另一个 我可以使用的属性?

    使用标准数据注释,不可以。您必须指定最大长度。只有其他参数是可选的。

    在这种情况下,我会推荐这样的东西:

    [StringLength(int.MaxValue, MinimumLength = 7)]
    

    你也可以像这样使用Regex(正则表达式)属性:

    [RegularExpression(@"^(?:.*[a-z]){7,}$", ErrorMessage = "String length must be greater than or equal 7 characters.")]
    

    更多信息在这里:Password Strength Validation with Regular Expressions

    【讨论】:

    • 谢谢莱尼尔。我已按照您的建议使用正则表达式来控制字符串长度。
    【解决方案2】:
    【解决方案3】:

    您是否考虑过删除数据注释并将 Html 属性添加到视图中的 Html.TextBoxFor 元素?

    应该看起来像:

    @Html.TextBoxFor(model => model.Full_Name, new { htmlAttributes = new { @class = "form-control", @minlength = "10" } })
    

    @Html.TextBoxFor(model => model.Full_Name, new { @class = "form-control",  @minlength = "10" } })
    

    10 是您选择的最小长度。

    我喜欢将 html 属性添加到我的视图中,因为我可以快速看到它的影响。不会弄乱您的数据库,并且如果您使用迁移(代码优先方法),则不需要您运行迁移和数据库更新。

    请记住,当您将 EditorFor 更改为 TextBoxFor 时,您的样式会丢失,但应该很容易修复,您可以再次将样式添加到视图或将样式添加到 CSS 文件。

    希望这会有所帮助:)

    【讨论】:

    • 这不会强制服务器上的限制。
    【解决方案4】:

    弗朗索瓦干得好, 似乎您不能使用数据注释在输入字段上发出 maxlength 属性。它只提供客户端验证。 使用带有 HTML 属性的 maxlength 创建了正确设置 maxlength 的输入字段。

    @Html.EditorFor(model => model.Audit_Document_Action, new { htmlAttributes = new { @class = "form-control", @maxlength = "10" } })
    

    【讨论】:

      猜你喜欢
      • 2011-01-24
      • 1970-01-01
      • 2012-06-09
      • 1970-01-01
      • 2023-04-03
      • 2012-05-30
      • 1970-01-01
      • 2015-09-30
      • 1970-01-01
      相关资源
      最近更新 更多