StringLengthAttribute

所述 StringLength 屬性指定被允許在一個資料欄位中的字元的最小和最大長度。此屬性可以應用於屬性,公共欄位和引數。必須在屬性的 ErrorMessage 屬性上指定錯誤訊息。 MinimumLengthMaximumLength 屬性分別指定最小值和最大值。

首先新增名稱空間:

using System.ComponentModel.DataAnnotations;

並在屬性上應用該屬性。

public class User
{
   // set the maximum
   [StringLength(20, ErrorMessage = "The username cannot exceed 20 characters. ")]
   public string Username { get; set; }

   [StringLength(MinimumLength = 3, MaximumLength = 16, ErrorMessage = "The password must have between 3 and 16 characters.")]        
   public string Password { get; set; }
}

還可以在錯誤訊息中使用資源用於全域性化應用程式。在這種情況下, ErrorMessageResourceName 必須與必須在被設定好的資源類(resx 檔案)的資源鍵指定 ErrorMessageResourceType

public class User
{
   [StringLength(20, ErrorMessageResourceName = "StringLength", 
                              ErrorMessageResourceType = typeof(ResoucesKeys))]        
   public string Username { get; set; }

   [StringLength(MinimumLength = 3, 
                        MaximumLength = 16, 
                        ErrorMessageResourceName = "StringLength", 
                        ErrorMessageResourceType = typeof(ResoucesKeys))]        
   public string Password { get; set; }
}