Model驗證是ASP.NET MVC中的重要部分,它主要用於判斷輸入的數據類型及值是否符合我們設定的規則,這篇文章就介紹下ASP.NET MVC中Model驗證的幾種方式。
后台驗證
DataAnnotation
DataAnnotation翻譯過來是“數據注解”的意思,DataAnnotation命名空間中包含一些用於驗證Model的特性,如:RequiredAttribute,CompareAttribute,DisplayAttribute等,我們在創建Model時,將相應的特性性標注到字段上即可實現數據驗證。
創建Model:
public class Person { [Display(Name = "姓名")] [Required(ErrorMessage = "姓名是必須的!")] public string Name { set; get; } [Display(Name = "姓名")] public int Age { set; get; } }
View中的代碼:
@model EBuy.Website.Models.Person @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <div> <h3 style="color:red;"> @Html.ValidationSummary() </h3> </div> <div> @using (Html.BeginForm("evaluate", "home", "Post")) { @Html.LabelFor(Model => Model.Name) @Html.TextBoxFor(Model => Model.Name) @Html.LabelFor(Model => Model.Age) @Html.TextBoxFor(Model => Model.Age) <input type="submit" value="提交" /> } </div> </body> </html>
Controller中的代碼:
public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult Evaluate(Person person) { if (ModelState.IsValid) { return Content("evaluate success!"); } return View("Index", person); } }
運行程序:

注意,Age屬性上並未標注RequiredAttribute,卻依然提示Age字段必須,這是因為Age是int類型,int類型不能為null,對於不能為null的類型,ASP.NET MVC默認為是必須的。除此之外,ASP.NET MVC還會幫助我們進行數據類型的驗證,如,若在年齡一欄輸入非整數,那么驗證將不會通過,且會提示數值不合法。
ValuationAttribute
除了使用DataAnnotation中預定義的一些特性進行數據驗證外,我們還可以自定義一些驗證特性。這里我們通過覆寫DataAnnotation命名空間中ValudationAttribute類的IsValid方法來實現自定義驗證。示例代碼如下:
public class CheckAgeAttribute : ValidationAttribute { private int _minage; public CheckAgeAttribute(int minAge) { _minage = minAge; } public override bool IsValid(object value) { if (value is int) { var age = value as int?; if (age == null) { return false; } if (age < _minage) { return false; } return true; } return false; } public override string FormatErrorMessage(string name) { return base.FormatErrorMessage(name); } }
標注特性:
public class Person { [Display(Name = "姓名")] [Required(ErrorMessage = "姓名是必須的!")] [MaxLength(4, ErrorMessage = "太長了")] public string Name { set; get; } [Display(Name = "年齡")] [CheckAge(18, ErrorMessage = "年紀太小!")] public int Age { set; get; } }
然后運行程序:

IValidatableObject
通過實現IValidatableObject接口進行數據的驗證,示例代碼如下:
public class Person : IValidatableObject { [Display(Name = "姓名")] public string Name { set; get; } [Display(Name = "年齡")] public int Age { set; get; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { Person person = validationContext.ObjectInstance as Person; if (person == null) { yield break; } if (string.IsNullOrEmpty(person.Name)) { yield return new ValidationResult("您貴姓?"); } if (person.Age < 18) { yield return new ValidationResult("太年輕了!"); } } }
運行程序:

IDataErrorInfo
實現IDataErrorInfo接口也可以進行數據的驗證,示例代碼如下:
public class Person : IDataErrorInfo { [Display(Name = "姓名")] public string Name { set; get; } [Display(Name = "年齡")] public int Age { set; get; } public string this[string columnName] { get { switch (columnName) { case "Name": if (string.IsNullOrEmpty(Name)) { return "雁過留聲,人過留名"; } return null; case "Age": if (Age < 18) { return "年紀尚輕!"; } break; } return null; } } public string Error { get { //若返回值不是""或null,則不管數據是否合法,則驗證都不會通過 //並且會在數據驗證成功后顯示此處指定的錯誤信息 return ""; //return "出錯啦!"; } } }
運行程序:

前端驗證
上述驗證均是在服務器端進行的,除此之外我們也可以使用js在客戶端進行數據的驗證。除了我們自己手寫js代碼外,ASP.NET MVC也提供了前端驗證方法,要啟用ASP.NET MVC提供的前端驗證方法需要在頁面中引入三個js文件:
- jquery-1.10.2.min.js(也可以是其它版本的jQuery)
- jquery.validate.min.js
- jquery.validate.unobtrusive.min.js
然后在配置文件中開啟客戶端驗證(默認是開啟的):
<configuration> <appSettings> <add key="ClientValidationEnabled" value="true"/> <add key="UnobtrusiveJavaScriptEnabled" value="true"/> </appSettings> </configuration>
注意:若要使ASP.NET MVC提供的前端驗證生效,需要對Model進行數據注解(DataAnnotation)。
引用文件之后,運行程序,然后查看頁面源代碼,可以看到form中的input標簽中多出了 data-val 屬性以及其它的和數據注解相關的屬性。
對於驗證失敗的信息,我們需要對用戶進行相應的提醒。只需要在<form></form>中添加 @Html.ValidationSummary() 即可。