jQuery验证控件jquery.validate.js使用说明+中文API
结合ASP.NET MVC中的运用,可以看蒋金楠大牛的博客,写的很系统,ASP.NET MVC的客户端验证:jQuery的验证.以及他相关的博客,写的非常好。
下面是我个人结合自己项目中的笔记:
Model的定义:
public class UserInfo { [Required] [StringLength(20, ErrorMessage = "UserName can not more than 20 chars")] public string UserName { get; set; } [Required] [StringLength(200)] public string Password { get; set; } }
View中的代码:
@model XXX.Model.User.UserInfo
<li> <p> Username </p> @Html.TextBoxFor(m => m.UserName) <br /> @Html.ValidationMessageFor(m => m.UserName) </li> <li> <p> Password </p> @Html.PasswordFor(m => m.Password) <br /> @Html.ValidationMessageFor(m => m.Password) </li>
生成的Html代码:
<li> <p> Username </p> <input data-val="true" data-val-length="UserName can not more than 20 chars" data-val-length-max="20" data-val-required="UserName 字段是必需的。" id="UserName" name="UserName" type="text" value="" /> <br /> <span class="field-validation-valid" data-valmsg-for="UserName" data-valmsg-replace="true"></span> </li> <li> <p> Password </p> <input data-val="true" data-val-length="字段 Password 必须是最大长度为 200 的字符串。" data-val-length-max="200" data-val-required="Password 字段是必需的。" id="Password" name="Password" type="password" /> <br /> <span class="field-validation-valid" data-valmsg-for="Password" data-valmsg-replace="true"></span> </li>
如果看过jquery.validate相关的文档,你可能会疑惑,jquery.validate一般都是把验证规则定义在css样式中,更规范的写法,独立写js,和html脱离开来。
<input class="required" id="name" name="name" type="text"/>or
<script type="text/javascript"> 1: 2: $(document).ready(function () { 3: $("form").validate({ 4: rules :{ 5: name :{required: true}, 6: birhthDate :{required: true, date: true}, 7: blogAddress :{url: true}, 8: emailAddress:{required: true, email: true} 9: }, 10: 11: messages: { 12: name :{ required: "请输入姓名" }, 13: birhthDate :{required: "请输入出生日期", date: "请输入一个合法的日期"}, 14: blogAddress :{ url: "请输入一个合法的URL" }, 15: emailAddress:{required: "请输入Email地址", email: "请输入一个合法的Email地址"} 16: } 17: }); 18: }); </script>
我们发现,在Model中设置了[Required]等特性,在前台不写一行js验证的代码,客户端已经实现了验证;后台只要调用一行代码ModelState.IsValid,就实现了服务器端的验证,是不是有web form中Page.IsValid的感觉,不用写验证的代码,是不是很爽?
if (ModelState.IsValid) { LoginResponse response = eServiceProxy.serviceProxy.Login(request); if (response != null && response.IsAuthenticated) { FormsAuthentication.SetAuthCookie(request.Username, true); return RedirectToAction("Index", "Home"); } else { ViewData["errorMsg"] = "Login Fail"; } }
可是,有没有很好奇,MVC生成的html中,没有定义规则的class,也没有生成相关的js来定义rules.甚至连调用验证的validate()方法都没有,它是如何触发验证的呢?