標籤:
model中的驗證註解特性:
public class StuInfo { public int ID { get; set;} [Display(Name = "姓名")] //設定要顯示的欄位名 [Required(ErrorMessage = "您需要填寫{0}")] //設定為必須欄位 已經錯誤提示 [StringLength(50, MinimumLength = 3)] //設定最大長度和最小長度 public string Name { get; set;} [Display(Name = "年齡")] [Range(1, 150, ErrorMessage = "年齡填寫不正確!")] //設定 值範圍 public int Age { get; set;} [Display(Name = "身高")] [Range(typeof(decimal),"50.00", "250.00",ErrorMessage = "身高超出指定範圍")] public decimal Height { get; set;} [Display(Name = "生日")] [DataType(DataType.Date,ErrorMessage = "{0}格式不正確")] //設定資料類型以及錯誤提示 public DateTime Birthday { get; set;} [Display(Name = "電話")] [Remote("CheckPhone","StuInfo", ErrorMessage = "{0}已被註冊")] //在指定的Conteroller中的通道(route)中驗證資料 public string Phone { get; set;} [Display(Name = "地址")] [DataType(DataType.MultilineText)] public string Address { get; set;} [Display(Name = "電子郵箱")] [RegularExpression(@"(\w)+(\.\w+)*@(\w)+((\.\w+)+)",ErrorMessage = "{0}格式不正確")] //正則驗證 public string Email { get; set;} [Display(Name = "再次輸入電子郵箱")] [Compare("Email",ErrorMessage = "{0}兩次輸入不一致")] //設定比較兩個欄位的值 public string EmailConfirm { get; set;} [Display(Name = "密碼")] [DataType(DataType.Password)] public string Password { get; set;} [Display(Name = "備用電子郵箱")] [DataType(DataType.EmailAddress,ErrorMessage = "{0}格式不正確")] public string email_B { get; set;}}
遠程驗證的通道:
public JsonResult CheckPhone(string phone) { var result= StuInfoBll.FindPhone(phone).count == 0; return Json(result, JsonRequestBehavior.AllowGet); }
效果:
正常下的網頁:
必須欄位驗證效果:
值範圍、實值型別驗證效果:
正則驗證和比較欄位值效果:
資料類型驗證效果:
MVC4資料註解和驗證