通過爲模型類增加數據描述的 DataAnnotations ,我們可以容易地爲應用程序增加驗證的功能。DataAnnotations 允許我們描述希望應用在模型屬性上的驗證規則,ASP.NET MVC 將會使用這些 DataAnnotations ,然後將適當的驗證信息返回給用戶。
常用的 DataAnnotations
- Required 必須 – 表示這個屬性是必須提供內容的字段
- DisplayName 顯示名 – 定義表單字段的提示名稱
- StringLength 字符串長度 – 定義字符串類型的屬性的最大長度
- Range 範圍 – 爲數字類型的屬性提供最大值和最小值
- Bind 綁定 – 列出在將請求參數綁定到模型的時候,包含和不包含的字段
- ScaffoldColumn 支架列 - 在編輯表單的時候,需要隱藏起來的的字符
- Compare 比較 - 與制定的字段值進行比較 具體見代碼
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace SKUOrderMVC.Models
{
public class ChangePassword
{
[Required]
[Display(Name = "Email")]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
[StringLength(32, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
}
當然還有其他的一些屬性,比如正則表達式等,不用輔助編碼就可以完成對數據輸入格式的驗證。