Asp.net mvc DataAnnotations StringLength属性MVC-无最大值
我在MVC4中使用数据注释进行模型验证,目前正在使用StringLengthAttribute,但是我不想指定最大值(当前设置为50),而是想指定最小字符串长度值 有没有办法只指定最小长度?也许我可以使用另一个属性 我目前的代码是:Asp.net mvc DataAnnotations StringLength属性MVC-无最大值,asp.net-mvc,asp.net-mvc-4,data-annotations,minimum,string-length,Asp.net Mvc,Asp.net Mvc 4,Data Annotations,Minimum,String Length,我在MVC4中使用数据注释进行模型验证,目前正在使用StringLengthAttribute,但是我不想指定最大值(当前设置为50),而是想指定最小字符串长度值 有没有办法只指定最小长度?也许我可以使用另一个属性 我目前的代码是: [Required] [DataType(DataType.Password)] [Display(Name = "Confirm New Password")] [StringLength(50, MinimumLength = 7
[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; }
有没有办法只指定最小长度?也许另一个
我可以使用的属性
使用标准数据注释,否。必须指定最大长度。只有其他参数是可选的
在这种情况下,我建议如下:
[StringLength(int.MaxValue, MinimumLength = 7)]
您还可以使用如下(正则表达式)属性:
[RegularExpression(@"^(?:.*[a-z]){7,}$", ErrorMessage = "String length must be greater than or equal 7 characters.")]
这里有更多信息:您是否考虑过删除数据注释并向视图中的Html.TextBoxFor元素添加Html属性 应该看起来像:
@Html.TextBoxFor(model => model.Full_Name, new { htmlAttributes = new { @class = "form-control", @minlength = "10" } })
或
10是您选择的最小长度
我喜欢在视图中添加html属性,因为我可以很快看到它的影响。如果您使用迁移(代码优先方法),则无需运行迁移和数据库更新,也不会影响数据库
请记住,当您将EditorFor更改为TextBoxFor时,您将失去样式设置,但这应该是一个简单的修复方法,同样,您可以将样式添加到视图中或将样式添加到CSS文件中
希望这有帮助:)为此,还有[MinLength(7)]属性
资料来源:干得好,弗朗索瓦,
似乎无法使用数据注释在输入字段上发出maxlength属性。它只提供客户端验证。
使用带有HTML属性的maxlength创建了正确设置maxlength的输入字段
@Html.EditorFor(model => model.Audit_Document_Action, new { htmlAttributes = new { @class = "form-control", @maxlength = "10" } })
谢谢你,莱尼尔。正如你所建议的,我已经求助于使用正则表达式来管理字符串长度。这并没有对服务器施加限制。
@Html.EditorFor(model => model.Audit_Document_Action, new { htmlAttributes = new { @class = "form-control", @maxlength = "10" } })