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

希望這有助於:)