When I was working on a project recently, I needed to use the jQuery.validate.js plug-in, so I recorded some of my experience at work for future study.
[Examples are as follows]
1. Front page
<form id="form1" method="post"> 用户名:<input type="text" id="UserName" name="UserName" /><!--<span id="name_error"></span>--> <br /> 密 码:<input type="password" id="Password" name="Password" /> <br /> <input type="submit" id="btnRegister" name="btnRegister" value="注册" /> <input type="button" id="btnCancel" name="btnCancel" value="取消" /> </form>
2.Javascript
<script type="text/javascript"> //添加自定义验证 jQuery.validator.addMethod("checkPWD", function (value, element) { var flag = false; //flag = chkpwd($("#pwd")); //自定义验证密码逻辑 return this.optional(element) || flag; }); $(function () { $("#form1").validate({ rules: { UserName: { required: true, //emote: function () { //验证用户名是否存在是否存在 方法一 // $.ajax({ // type: 'POST', // url: "Handler/Handler1.ashx", // data: { name: $("#UserName").val() }, // async: false, // success: function (data) { // $("#name_error").html(data); // } // }); //} remote: { //验证用户名是否存在是否存在 方法二 type: "POST", url: "Handler/Handler1.ashx", //后台处理程序 dataType: "json", //接受数据格式 data: { //要传递的参数 action: function () { return "CheckName" }, name: function () { return $("#UserName").val(); }, param1: function () { return "自定义参数1"; } } } }, Password: { required: true, checkPWD: true //自定义验证,若想不用自定义验证,把 true 改成 false 即可。 } }, messages: { "UserName": { required: "<span>用户名不能为空.</span>", remote: "<span>该会员名已存在!</span>" }, "Password": { required: "<span>密码不能为空.</span>", checkPWD: "<span>密码不符合自定义规则。。。</span>" } } }); }) </script>
3. Background processing program
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string action = context.Request["action"]; //获取用户名和自定义参数 string name = context.Request["name"]; string param1 = context.Request["param1"]; if (!string.IsNullOrEmpty(name)) { //模拟查询数据库,如果用户输入的是 admin ,则提示该账户已存在,返回 false if (name.Equals("admin")) { context.Response.Write("false"); } else { context.Response.Write("true"); } } }
4. Running results
4.1 An error occurs when the user does not enter data:
4.2 Error when user enters wrong information: