一、启用客户端验证(即jquery验证):
1、web.config:
<add key="ClientValidationEnabled" value="true"/> <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
2、验证页面引用jquery:
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
3、显示消息,true既无不显示消息汇总,在下面
ValidationMessageFor 处显示验证消息
@Html.ValidationSummary(true)
@Html.ValidationMessageFor(m => m.UserName)
4、在model类中对要验证的字段上方加 [Required],除了Required,我们还可以在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; }
5、调用后台远程验证--即不提交验证 如:登录时不提交判断用户是否存在
在要 验证的model里上面加
CheckUserName:对应的action方法名,User:对应的控制器名称。
public JsonResult CheckUserName(string userName) //对应页面传值名称,不区分大小写 { bool isValidate = false; var b = OwnDb.UserModel.FirstOrDefault(a => a.UserName == userName); //假设让某个username不通过 if (b != null) { isValidate = true; } //Remote验证是通过get方式请求的 return Json(isValidate, JsonRequestBehavior.AllowGet); }
效果:
二、后台验证(只客户端验证肯定是不安全的)
[HttpPost] public ActionResult Login(UserModel m) { if (string.IsNullOrEmpty(m.UserName)) { ModelState.AddModelError("UserName", "用户名 字段是必需的。"); //在页面显示验证提示 } if (string.IsNullOrEmpty(m.Password)) { ModelState.AddModelError("Password", "密码 字段是必需的。");//在页面显示验证提示 } if (ModelState.IsValid) //判断验证是否通过 { } return View(); }