向MVC的Model中添加驗證

ASP.NET MVC 的核心設計原則之一是DRY(Don’t Repeat Yourself)——”不要重複自己”。在Model中添加驗證可以省去我們在服務器端對數據的進行的繁瑣驗證操作。用好驗證特性可以使代碼更簡潔,易擴展,易維護。

向MVC的Model中添加驗證特性:

MVC的服務端驗證流程是這樣的:
客戶端請求—>Route解析—> model綁定—> 數據驗證.

命名空間:using System.ComponentModel.DataAnnotations;

舉個栗子:

public class Model
{
    public int ID { get; set; }

    [StringLength(60, MinimumLength = 3)]
    public string Name { get; set; }

    [Display(Name = "Registe Date")]
    [DataType(DataType.Date)]
    public DateTime Date { get; set; }

    [RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")] 
    [Required]
    [StringLength(30)]
    public string Genre { get; set; }

    [Range(1, 100)]
    [DataType(DataType.Currency)]
    public decimal Price { get; set; }

}

驗證特性種類:

  1. [Required] : 必填項
    [Required(ErrorMessage = "請輸入姓名")]

  2. [StringLength] : 限制字符串長度
    [StringLength(MaximumLength = 10 , MinimumLength = 3,ErrorMessage = "字符長度在3~10之間")]

  3. [Range] : 限制取值範圍
    [Range(0, 120, ErrorMessage = "取值範圍在0~120之間")]

  4. [RegularExpression] : 匹配符合某個正則表達式
    [RegularExpression(@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage = "請輸入正確的Email")]

  5. Compare :判等比較
    [Compare("Pwd", ErrorMessage = "兩次密碼不一致")]

  6. Remote : Ajax遠程驗證,返回值是bool類型 true表示驗證通過

    //ValideUser爲行爲Action,Validate爲控制器Controller
    [Remote("ValideUser", "Validate", HttpMethod = "post", ErrorMessage = "用戶名已存在")]
    public string UserName { get; set; }  
    
    public IActionResult ValideUser()  
    {   
    if(//條件...)  
    {  
    return Json(true,JsonRequestBehavior.AllowGet);  
    }  
    else  
    return Json(false,JsonRequestBehavior.AllowGet);  
    }  
  7. OutputCache :設置頁面緩存

    //Duration單位:秒
    [OutputCache(Duration=20)] 
    public IActionResult Index()  
    {  
     //......
    }  
  8. 自定義正則驗證特性

    public class EmailValid : RegularExpressionAttribute  
    {  
        public EmailValid ()  
            :base(@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$")  
        {  
        }  
    }  
  9. 擴展驗證特性

    實現服務器+客戶端驗證:繼承ValidationAttribute ,實現IClientValidatable 接口

    public class CheckAttribute : ValidationAttribute ,IClientValidatable 
    { 
       //重寫IsValid驗證方法
       public override bool IsValid(object value) 
       { 
           if (value == null) return false; 
           if (value.GetType() != typeof(bool)) 
               throw new InvalidOperationException("只能用於Bool屬性"); 
           return (bool)value; 
       }
    
       //重寫 FormatErrorMessage錯誤消息提示方法
       public override string FormatErrorMessage(string name) 
       { 
           return name==null?"請仔細閱讀相關協議":name; 
       }
    
       //實現GetClientValidationRules方法
       public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) 
      { 
        yield return new ModelClientValidationRule 
        { 
            ErrorMessage = String.IsNullOrEmpty(ErrorMessage) ? FormatErrorMessage(metadata.DisplayName) : ErrorMessage, 
            ValidationType = "checkfocus" 
        }; 
      }     
    }

    通過實現IClientValidatable接口,使程序在生成html代碼時候,爲相應的input添加上了額外的驗證規則,但是這些規則在客戶端上,還沒有方法來啓動驗證。
    添加JQuery代碼:

    //添加ValidationType 
    <script type="text/javascript"> 
      jQuery.validator.addMethod("checkfocus", function(value, element, param) { 
          return element.checked; 
      }); 
      jQuery.validator.unobtrusive.adapters.addBool("checkfocus"); 
    </script>

數據格式化特性

  1. DisplayName:設定字段顯示的名字
    [DisplayName("User Name")]

  2. DataType:用於視圖引擎對數據進行格式化

    [DataType(DataType.EmailAddress)] 郵箱
    
    [DataType(DataType.CreditCard)]​​   信用卡
    
    [DataType(DataType.Currency)]​   貨幣
    
    [DataType(DataType.Date)]​   日期
    
    [DataType(DataType.DateTime)]​   日期時間
    
    [DataType(DataType.Html)]HTML文件
    
    [DataType(DataType.ImageUrl)]​   圖片的URL
    
    [DataType(DataType.MultilineText)]​   多行文本
    
    [DataType(DataType.Password)]​   密碼值
    
    [DataType(DataType.PhoneNumber)]    電話號碼值
    
    [DataType(DataType.PostalCode)]​​   郵政代碼
    
    [DataType(DataType.Time)]​   時間
    
    [DataType(DataType.Upload)]​  文件上載數據類型
    
    [DataType(DataType.Url)]URL
  3. ReadOnly:指定該特性所綁定到的屬性是隻讀屬性
    [ReadOnly(true)]

總結

擴展驗證特性的使用:
1. 服務端創建驗證屬性類並繼承ValidationAttribute, 實現服務端的驗證。
2. 驗證屬性類實現IClientValidatable接口,爲生成的input標籤添加客戶端驗證規則,同時擴展客戶端驗證方法。

附加內容:模型綁定

MVC 包含幾種與默認綁定源不同行爲的 Attribute 。

[BindRequired]:表示如果這個綁定不能發生,將添加一個模型狀態錯誤(Model State Error)。

[BindNever]:表示這個參數不進行綁定。

[FromServices]:表示使用 dependency injection 通過服務來綁定參數。

[FromBody]:從 HTTP 請求的 Body 中綁定數據。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章