步步为营-85-注册信息验证
注册信息验证:
1 前台验证(js+Ajax):
首先像"邮箱格式","非空"验证可以通过js+正则表达式来完成;
另外像"用户名是否存在","邮箱是否已使用"可通过 Ajax向后台页面发请求,实现无页面刷新的验证()
2 仅仅是前台验证会存在一定的安全隐患,所以当用户提交时候还要实现后台验证
<form id="formRegister" name="formRegister" method="post"> <table width="80%" height="22" border="0" align="center" cellpadding="0" cellspacing="0" id="tableRegister"> <tr> <td width="2" bgcolor="#DDDDCC"> </td> <td> <div align="center"> <table height="61" cellpadding="0" cellspacing="0" style="height: 332px"> <tr> <td height="33" colspan="6"> <p class="STYLE2" style="text-align: center">注册新帐户方便又容易</p> </td> </tr> <tr> <td width="24%" align="center" valign="top" style="height: 26px">用户名</td> <td valign="top" width="37%" align="left" style="height: 26px"> <input type="text" name="LoginId" id="LoginId" /> <span id="msgName" style="font-size: 14px; color: red">*</span> </td> </tr> <tr> <td width="24%" height="26" align="center" valign="top">真实姓名:</td> <td valign="top" width="37%" align="left"> <input type="text" name="txtRealName" id="txtRealName" /> <span id="msgRealName" style="font-size: 14px; color: red">*</span> </td> </tr> <tr> <td width="24%" height="26" align="center" valign="top">密码:</td> <td valign="top" width="37%" align="left"> <input type="password" name="txtPwd" id="txtPwd" /> <span id="msgPwd" style="font-size: 14px; color: red">*</span> </td> </tr> <tr> <td width="24%" height="26" align="center" valign="top">确认密码:</td> <td valign="top" width="37%" align="left"> <input type="password" name="txtConfirmPwd" id="txtConfirmPwd" /> <span id="msgConfirmPwd" style="font-size: 14px; color: red">*</span> </td> </tr> <tr> <td width="24%" height="26" align="center" valign="top">Email:</td> <td valign="top" width="37%" align="left"> <input type="text" name="txtEmail" id="userMail" /> <span id="msgEamil" style="font-size: 14px; color: red">*</span> </td> </tr> <tr> <td width="24%" height="26" align="center" valign="top">地址:</td> <td valign="top" width="37%" align="left"> <input type="text" name="txtAddress" id="txtAddress" /> <span id="msgAddress" style="font-size: 14px; color: red">*</span> </td> </tr> <tr> <td width="24%" height="26" align="center" valign="top">手机:</td> <td valign="top" width="37%" align="left"> <input type="text" name="txtPhone" id="txtPhone" /> <span id="msgPhone" style="font-size: 14px; color: red">*</span> </td> </tr> <tr> <td width="24%" align="center" valign="top" class="auto-style1">验证码:</td> <td valign="top" width="37%" align="left" class="auto-style1"> <input type="text" name="txtCode" id="validateCode" /> <span id="validateCodeMsg" style="font-size: 14px; color: red">*</span> <img src="/ashx/ValidateCode.ashx" /></td> </tr> <tr> <td colspan="2" align="center"> <input type="button" value="注册" class="regnow" id="btnRegister" /></td> </tr> <tr> <td colspan="2" align="center"> </td> </tr> </table> <div class="STYLE5">---------------------------------------------------------</div> </div> </td> <td width="2" bgcolor="#DDDDCC"> </td> </tr> </table> </form>
<script type="text/javascript"> $(function () { //验证用户名 $('#LoginId').blur(function () { var val = $('#LoginId').val(); if (isNullOrEmpty(this)) { if (isNamingConventions(this)) { //判断用户名是否存在 $.post("/ashx/ValidateReg.ashx", { "action": "name", "loginName": val }, function (data) { $("#msgName").css("display", "inline"); warnMsg("#msgName", data); }) warnMsg("#msgName", "√"); } else { warnMsg("#msgName", "用户名只能是数字、字母、下划线 !"); } } else { warnMsg("#msgName", "用户名不能为空 !"); } }); //验证姓名 $('#txtRealName').blur(function () { if (isNullOrEmpty(this)) { warnMsg("#msgRealName", "√"); } else { warnMsg("#msgRealName", "真实姓名不能为空 !"); } }); //验证密码 $('#txtPwd').blur(function () { if (isNullOrEmpty(this)) { warnMsg("#msgPwd", "√"); } else { warnMsg("#msgPwd", "密码不能为空 !"); } }); //验证确认密码 $('#txtConfirmPwd').blur(function () { if (isNullOrEmpty(this)) { if ($('#txtConfirmPwd').val() != $('#txtPwd').val()) { warnMsg("#msgConfirmPwd", "密码不一致 !"); } else { warnMsg("#msgConfirmPwd", "√"); } } else { warnMsg("#msgConfirmPwd", "密码不能为空 !"); } }); //验证邮箱 $('#userMail').blur(function () { validateEmail(); }); //验证地址 $('#txtAddress').blur(function () { if (isNullOrEmpty(this)) { warnMsg("#msgAddress", "√"); } else { warnMsg("#msgAddress", "地址不能为空 !"); } }); //验证手机 $('#txtPhone').blur(function () { if (isNullOrEmpty(this)) { if (isNan(this)) { warnMsg("#msgPhone", "√"); } else { warnMsg("#msgPhone", "手机号只能为数字 !"); } } else { warnMsg("#msgPhone", "手机号不能为空 !"); } }); //验证验证码 $('#validateCode').blur(function () { validateCode(); }); //注册 $("#btnRegister").click(function () { validateEmail(); validateCode(); var par = $("#aspnetForm").serializeArray(); par = JSON.stringify(par); $.post("/ashx/UserRegister.ashx", { "parameter": par }, function (data) { alert(data); }); }); }); //验证"邮箱" function validateEmail() { var val = $('#userMail').val(); if (val != "") { var reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/; if (reg.test(val)) { //隐藏消息 $("#msgEamil").css("display", "none"); //发送给Ajax校验 $.post("/ashx/ValidateReg.ashx", { "action": "mail", "userMail": val }, function (data) { $("#msgEamil").css("display", "inline"); warnMsg("#msgEamil", data); }); } else { warnMsg("#msgEamil", "邮箱格式错误 !"); } } else { warnMsg("#msgEamil", "邮箱不能为空 !"); } }; //验证"验证码" function validateCode() { var val = $('#validateCode').val(); if (val != "") { var reg = /^[0-9]*$/; if (reg.test(val)) { //隐藏消息 $("#validateCodeMsg").css("display", "none"); //发送给Ajax校验 $.post("/ashx/ValidateReg.ashx", { "action": "code", "validateCode": val }, function (data) { $("#validateCodeMsg").css("display", "inline"); warnMsg("#validateCodeMsg", data); }); } else { warnMsg("#validateCodeMsg", "验证码格式错误 !"); } } else { warnMsg("#validateCodeMsg", "验证码不能为空 !"); } }; //显示警告 function warnMsg(span, msg) { if (span != null) { $(span).text(msg); } } </script>
注意 验证"邮箱"的时候有一句
$.post("/ashx/ValidateReg.ashx", { "action": "mail", "userMail": val }, function (data) {
$("#msgEamil").css("display", "inline");
warnMsg("#msgEamil", data);
});
using BookShopManager.Web.Common; using System; using System.Collections.Generic; using System.Web; using System.Web.SessionState; namespace BookShopManager.Web.Ashx { /// <summary> /// ValidateReg 的摘要说明 /// 前台页面校验 /// </summary> public class ValidateReg : IHttpHandler, IRequiresSessionState { BLL.Users UserManager = new BLL.Users(); public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string action = context.Request["action"]; if (action == "mail") { CheckedUserMail(context); } else if (action == "code") { string validateCode = context.Request["validateCode"]; if (ValidateCode.CheckValidateCode(validateCode)) { context.Response.Write("√"); } else { context.Response.Write("验证码错误"); } } else if (action == "name") { string loginName = context.Request["loginName"]; if (UserManager.ExistsByUserName(loginName)) { context.Response.Write("用户名已存在"); } else { context.Response.Write("√"); } } } #region 校验邮箱 private void CheckedUserMail(HttpContext context) { string userMail = context.Request["userMail"]; if (UserManager.ExistsByUserMail(userMail)) { context.Response.Write("邮箱已使用"); } else { context.Response.Write("√"); } } #endregion public bool IsReusable { get { return false; } } } }
另外当点击"注册"按钮后,将表单元素序列化为json数组对象
var par = $("#aspnetForm").serializeArray();
par = JSON.stringify(par);
$.post("/ashx/UserRegister.ashx", { "parameter": par }, function (data) { alert(data); });
需要在后台引用 命名空间来实现反序列化
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
JArray ja = (JArray)JsonConvert.DeserializeObject(jsonStr);//反序列化
using System; using System.Collections.Generic; using System.Web; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.ServiceModel; using System.ServiceModel.Web; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using System.Web.Script.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using BookShopManager.Web.Common; using BookShopManager.BLL; using System.Web.SessionState; using BookShopManager.Web.Enum; using System.Web.UI; namespace BookShopManager.Web.Ashx { /// <summary> /// UserRegister 的摘要说明 /// 注册按钮后 进行"校验"和"新增" /// </summary> public class UserRegister : IHttpHandler, IRequiresSessionState { //"用户注册"服务端校验 public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string strJson = context.Request["parameter"]; Model.Users userInfo; BLL.Users userManager = new BLL.Users(); string msg = string.Empty; if (ValidateUserInfo(strJson, out msg, out userInfo)) { //校验成功,进行添加 if (userManager.Add(userInfo) > 0) { string strScript = "<script type='text/javascript'>alert('" + "注册成功" + "');window.location.href='" + "../Default.aspx" + "'</script>"; HttpContext.Current.Session["vCode"] = null; context.Session["userInfo"] = userInfo; context.Response.Redirect("<script type='text/javascript'>alert('" + "注册成功" + "');</script>"); } else { //跳到错误页面 context.Response.Redirect("/ShowMsg.aspx?msg=" + "注册失败" + "&title=首页" + "&url=/Default.aspx"); } } else { context.Response.Write(msg); } } private bool ValidateUserInfo(string jsonStr,out string msg, out Model.Users UserInfo) { JArray ja = (JArray)JsonConvert.DeserializeObject(jsonStr); UserInfo = new Model.Users(); BLL.Users UserManager = new BLL.Users(); UserInfo.LoginId = ja[1]["value"].ToString(); //用户名 UserInfo.Name = ja[2]["value"].ToString(); //真实姓名 UserInfo.LoginPwd = ja[3]["value"].ToString(); //密码: string confirmPwd = ja[4]["value"].ToString(); //确认密码 UserInfo.Address = ja[6]["value"].ToString(); //地址: UserInfo.Phone = ja[7]["value"].ToString(); //手机: UserInfo.Mail = ja[5]["value"].ToString(); //Email: string validate = ja[8]["value"].ToString(); //验证码: msg = string.Empty; if (string.IsNullOrEmpty(UserInfo.LoginId)) { msg += "用户名不能为空!! \n"; } if (string.IsNullOrEmpty(UserInfo.Name)) { msg += "真实姓名不能为空!! \n"; } if (string.IsNullOrEmpty(UserInfo.LoginPwd)) { msg += "密码不能为空!!\n "; } if (string.IsNullOrEmpty(confirmPwd)) { msg += "确认密码不能为空!!\n "; } if (string.IsNullOrEmpty(UserInfo.Address)) { msg += "地址不能为空!!\n "; } if (string.IsNullOrEmpty(UserInfo.Phone)) { msg += "手机号不能为空!!\n "; } if (string.IsNullOrEmpty(UserInfo.Mail)) { msg += "邮箱不能为空!!\n "; } if (string.IsNullOrEmpty(validate)) { msg += "验证码不能为空!!\n "; } if (msg.Length > 1) { return false; } //判断密码是否一致 if (UserInfo.LoginPwd != confirmPwd) { msg += "两次密码输入不一致!! \n"; return false; } //校验验证码是否正确 if (!ValidateCode.CheckValidateCode(validate)) { msg += "验证码不正确!! \n"; return false; } //校验邮箱是否已使用, if (UserManager.ExistsByUserMail(UserInfo.Mail)) { msg += "邮箱已使用!! \n"; return false; } //用户名是否存在 if (UserManager.ExistsByUserName(UserInfo.LoginId)) { msg += "用户名已存在!! \n"; return false; } UserInfo.UserStateId = ConvertHelper.ToInt(UserSatateEnum.NormalState.GetHashCode()); return true; } public bool IsReusable { get { return false; } } bool IHttpHandler.IsReusable { get { throw new NotImplementedException(); } } } }