MVC Model验证
Model类中可以添加的验证标记:
1. 必填字段
[Required]
public string FirstName { get; set; }
2. 字段长度
至多n位:
[StringLength(160)]
public string FirstName { get; set; }
要求至少n位:
[StringLength(160, MinimumLength=3)]
public string FirstName { get; set; }
3. 正则验证
[RegularExpression(@”[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}”)]
public string Email { get; set; }
4. 范围
[Range(35,44)]
public int Age { get; set; }
小数的情况:
[Range(typeof(decimal), “0.00”, “49.99”)]
public decimal Price { get; set; }
5. 服务端参与的验证
[Remote(“CheckUserName”, “Account”)]
public string UserName { get; set; }
然后在AccountController里指定一个CheckUserName方法:
public JsonResult CheckUserName(string username) { var result = Membership.FindUsersByName(username).Count == 0; return Json(result, JsonRequestBehavior.AllowGet); }
6. 比较
[RegularExpression(@”[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}”)]
public string Email { get; set; }
[Compare(“Email”)]
public string EmailConfirm { get; set; }
7. 自定义错误消息
正则:
[RegularExpression(@”[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}”,
ErrorMessage=”Email doesn’t look like a valid email address.”)]
public string Email { get; set; }
普通文本:
[Required(ErrorMessage=”Your last name is required”)]
[StringLength(160, ErrorMessage=”Your last name is too long”)]
public string LastName { get; set; }
占位符:
[Required(ErrorMessage=”Your {0} is required.”)]
[StringLength(160, ErrorMessage=”{0} is too long.”)]
public string LastName { get; set; }
三、后台Action的写法
Action里要做的有两件事:判断ModelState是否合法、添加错误消息。MVC3模板自带的登录Action如下:
[HttpPost] public ActionResult LogOn(LogOnModel model, string returnUrl) { if (ModelState.IsValid) { if (Membership.ValidateUser(model.UserName, model.Password)) { FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe); if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) { return Redirect(returnUrl); } else { return RedirectToAction("Index", "Home"); } } else { ModelState.AddModelError("", "The user name or password provided is incorrect."); } } // If we got this far, something failed, redisplay form return View(model); }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。