22

我在MVC4中使用数据注释进行模型验证,并且当前使用StringLengthAttribute,但是我不想指定最大值(当前设置为50),但是要指定最小值字符串长度值。DataAnnotations StringLength属性MVC - 没有最大值

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

我当前的代码是:

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

任何帮助深表感谢。

回答

34

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

使用标准数据注释编号您必须指定MaximumLength。只有其他参数是可选的。

在这种情况下,我建议是这样的:

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

您还可以使用正则表达式(正则表达式)属性像这样的:

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

更多内容这里:Password Strength Validation with Regular Expressions

+0

感谢Leniel。正如你所建议的那样,我使用正则表达式来控制字符串长度。 – davey1990 2012-07-10 00:15:28

1

你有没有想过删除数据注释并添加一个Html属性到你的Vie中的Html.TextBoxFor元素W'

应该是这个样子:

@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文件。

希望这有助于:)

相关问题