ASP.NET MVC-驗證

  • 317
  • 0

寫程式也一段時間,一直沒去搞懂一些東西

認真下定決心要去弄懂一些基礎知識

如有說錯也可以糾正<(-_-)>

在寫程式時,通常都會有一些基本防呆的檢查,長度檢查、必填檢查、格式檢查等等

在MVC中。可以透過對Model設定標籤,做到一些簡單的驗證

在後端透過ModelState.Isvalid判斷是否檢查通過

1.長度檢查

使用StringLength限制欄位的長度、還有另外一種MaxLength、MinLength

public class Product
{
   [StringLength(10)]
   public string ProductName { get; set; }
}

//還有限制最小長度的屬性、跟錯誤訊息設定
public class Product
{
   [StringLength(10,ErrorMessage ="{0}長度需介於{2}到{1}",MinimumLength =5)]
   public string ProductName { get; set; }
}

//還有MaxLength和MinLength
public class Product
{
    [MaxLength(50,ErrorMessage ="最常限制50字")]
    public string ProductName { get; set; }
    [MinLength(3,ErrorMessage ="作者名稱要三個字")]
    public string Ahthor { get; set; }
}

2.欄位必填

使用Required

public class Product
{
   [Required(ErrorMessage ="必填欄位")]
   public string Price { get; set; }
}

3.範圍檢查

第一個數字是最小值,第二個數值是最大值

使用Range,通常用於數字範圍的檢查

如果要比較日期,要使用typeof參數

public class Product
{
    Range(1,100,ErrorMessage ="在1~100之間")]
    public int Amount { get; set; }
    //檢查日期在某一段範圍之內
    [Range(typeof(DateTime),"2014/5/1","2014/5/31")]
    public DateTime DeadDate { get; set; }
}

4.正則式驗證

使用RegularExpression,驗證欄位格式是否符合正則式規則

public class Product
{        
   [RegularExpression(@"^[a-zA-Z''-'\s]{1,10}$")]
    public string Email { get; set; }
}

5.檢查兩個欄位是否一致

通常填寫表單時,會再讓使用者在輸入一次,確認資料一樣

像是密碼變更、或是電子郵件確認

就可以使用Compare

public class Product
{
   [Compare("ConfirmPassword")]
    public string Password { get; set; }
    public string ConfirmPassword { get; set; }
}

6.自定義驗證

如果內建標籤滿足不了,可以自己寫驗證邏輯,可以使用CustomValidation

1.建立一個類別

2.新增一個回傳ValidationResult的靜態方法,一定要兩個參數,一個是要驗證的欄位資料,一個就是ValidationContext(也可以不用)

3.在要驗證的屬性上加入標籤,CustomValidation(typeof(類別名稱), "方法名稱")]

public class Product
{
   [CustomValidation(typeof(CustomVali), "Invalid")]
   public string ProductName { get; set; }
}

public class CustomVali
{
   public static ValidationResult Invalid(string productname,ValidationContext validationContext)
   {
       return productname != null ? new ValidationResult("要填寫") : ValidationResult.Success;
   }
}