先上HTML代码:
1 <form id="login" name="login" action="~/f_login/Login" method="post"> 2 用户名:<input name="cuName" type="text" value="用户名/手机号" 3 onfocus="if (value == '用户名/手机号') { value = '' }" 4 onblur="if (value == '') { value = '用户名/手机号' }" /><br /> 5 密码:<input name="cPwd" type="password"><br /> 6 7 验证码:<input type="text" id="valText" name="code" /> 8 <img alt="验证码" id="validimg" src="@Url.Action("CreateImage","ValidationCode")" /> 9 10 <br /> 11 <input type="submit" id="flogin" value="登录" /> 12 <input type="reset" id="flogin" value="取消" /> 13 </form>
再上Jquery代码:
1 <script type="text/javascript" src="~/Scripts/jquery-1.8.2.min.js"></script> 2 <script type="text/javascript" src="~/Scripts/jquery.validate.min.js"></script> 3 <script type="text/javascript"> 4 $(document).ready(function () { 5 $("form").validate({ 6 rules :{ 7 cuNmae : { required: true }, 8 cPwd: { required: true }, 9 code: {required:true} 10 //birhthDate :{required: true, date: true}, 11 //blogAddress :{url: true}, 12 //emailAddress:{required: true, email: true} 13 }, 14 messages: { 15 cuName: { required: "请输入姓名" }, 16 cPwd: { required: "请输入密码" }, 17 code: {required:"请输入验证码"} 18 //birhthDate :{ required: "请输入出生日期", date: "请输入一个合法的日期"}, 19 //blogAddress :{ url: "请输入一个合法的URL" }, 20 //emailAddress:{ required: "请输入Email地址", email: "请输入一个合法的Email地址"} 21 } 22 }); 23 }); 24 </script>
注意点:
1.页面中的Jquery库不能重复包含,否则出错不生效;
2.jquery库必须添加到$("form").validate()方法之前,否则不生效;
3.验证规则和input控件中的name属性相对应。
4.本例子主要展示的是required规则,即不可为空,其它规则请查看jquery.validate.js文档
参考资料:《asp.net mvc 4 框架揭秘》 蒋金楠著