MVC4資料註解和驗證

來源:互聯網
上載者:User

標籤:

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資料註解和驗證

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.