ajax表单验证-可自定义填写则验证
使用ajax进行表单验证,不是什么新鲜事了,如何控制自如呢?假如你有以下需求
1,验证不通过不显示提交按钮
2,表单中有若干项,不是必须填写的,若填写,则进行验证
3,表单中若干项,必须填写必须验证
你不妨参考以下例子,本示例ajax处理采用asp,当然你可以改写成其他语言?
?index.html页面代码如下
?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><script src="ajax.js" language="javascript" type="application/javascript" ></script><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>AJAX表单验证</title></head><body><form id="form1" name="form1" method="post" action=""><table width="744" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td width="230">用户名(长度大于8,qwer已存在):</td> <td width="293"> <input name="txtUsername" type="text" id="txtUsername" size="40" /></td> <td height="20" ><img src="yes.gif" width="16" height="16" style="display:none" id="imgUsernameCorrect"/><img src="no.gif" width="16" height="16" style="display:none" id="imgUsernameError"/><div id="txtUsernameError" style="float:right;" ></div></td> </tr> <tr> <td width="230">密码(长度大于8):</td> <td><input name="txtPassword" type="password" id="txtPassword" size="40" /> </td> <td ><img src="yes.gif" width="16" height="16" style="display:none" id="imgPasswordCorrect" /><img src="no.gif" width="16" height="16" style="display:none" id="imgPasswordError" /><div id="txtPasswordError"></div></td> </tr> <tr> <td width="230">电子邮件:</td> <td><input name="txtEmail" type="text" id="txtEmail" size="40" /></td> <td><img src="Yes.gif" width="16" height="16" style="display:none" id="imgEmailCorrect" /><img src="no.gif" width="16" height="16" style="display:none" id="imgEmailError" /><div id="txtEmailError"></div></td> </tr> <tr> <td width="230"> </td> <td><input type="submit" onclick="javascript:confirm('感谢你参与测试!!!');" name="submit" id="btnSubmit" value="还不能注册,请按格式规范填写各项信息" /></td> <td width="221"> </td> </tr></table></form></body></html>
?
?
?
?
ajax.js文件如下
var oXmlHttp;function createXMLHttpRequest() { if(window.ActiveXObject) { oXmlHttp = new ActiveXObject("Microsoft.XMLHttp"); } else if(window.XMLHttpRequest) { oXmlHttp = new XMLHttpRequest(); }}function isFormValid () { var frmMain = document.forms[0]; var blnValid = true; for(var i=0;i < frmMain.elements.length;i++) { if(typeof frmMain.elements[i].valid == "boolean") { blnValid = blnValid && frmMain.elements[i].valid; } } return blnValid;}function validateField(oEvent) { oEvent = oEvent || window.event; var txtField = oEvent.target || oEvent.srcElement; createXMLHttpRequest();//zXmlHttp.createRequest(); oXmlHttp.open("get","validate.asp?" + txtField.name + "=" + encodeURIComponent(txtField.value),true); oXmlHttp.onreadystatechange = function () { if (oXmlHttp.readyState == 4) { if (oXmlHttp.status == 200) { var arrInfo = oXmlHttp.responseText.split("||");var imgError = document.getElementById("img"+txtField.id.substring(3)+"Error");var imgCorrect =document.getElementById("img"+txtField.id.substring(3)+"Correct");var txtError = document.getElementById("txt"+txtField.id.substring(3)+"Error");var btnSubmit = document.getElementById("btnSubmit");if (!eval(arrInfo[0])) { imgError.title = arrInfo[1]; imgError.style.display = ""; imgCorrect.style.display="none"; txtError.style.display = ""; txtError.innerHTML = arrInfo[1]; txtField.valid = false; } else { imgError.style.display = "none"; imgCorrect.style.display=""; txtField.valid = true; txtError.style.display = "none"; }if (isFormValid()){btnSubmit.disabled = false;btnSubmit.value = "注册";}else{ btnSubmit.disabled = true;}} else { alert("An error occured while trying to contact the server");}} }; oXmlHttp.send(null);}window.onload = function () { if (1) { var btnSubmit = document.getElementById("btnSubmit"); var txtUsername = document.getElementById("txtUsername"); var txtPassword = document.getElementById("txtPassword"); var txtEmail = document.getElementById("txtEmail"); btnSubmit.disabled = true; txtUsername.onchange = validateField; txtPassword.onchange = validateField; txtEmail.onchange = validateField; txtUsername.valid = false; txtPassword.valid = false;//设为FALSE,必须从填写,进行验证 txtEmail.valid=true;//设为true,则可以为空,如果填写,则进行验证 }};
?
?
?
validate.asp 页面代码如下
<%response.Charset="gb2312" valid = "false" message = "an unknown error occurred" ' txtPassword=request.QueryString("txtPassword") ' txtUsername=request.QueryString("txtUserName")'txtEmail=request.QueryString("txtEmail") 'if request.QueryString<>"" then if(not isEmpty(request.QueryString("txtPassword") )) then if (len(request.QueryString("txtPassword"))<8) then message = "密码要大于8个字符!" elseif (request.QueryString("txtPassword")="") then message = "密码不能为空!" else valid = "true" message = "1" end if elseif(not isEmpty(request.QueryString("txtUsername"))) then if (request.QueryString("txtUsername") = "qwer") then message = " 该用户名已被注册!请换一个用户名! " elseif (len(request.QueryString("txtUsername")) < 8 and request.QueryString("txtUsername") <> "") then message = "用户名要大于8个字符!" elseif (request.QueryString("txtUsername")= "")then message = "用户名不能为空 !" else valid = "true" message = "" end if elseif(not isEmpty(request.QueryString("txtEmail"))) then if(not IsValidEmail(request.QueryString("txtEmail")) ) then message = "请您填写正确的email地址!" else valid = "true" message = "" end if end if response.Write valid&"||"&message %>
?
<%function IsValidEmail(email) dim names, name, i, c IsValidEmail = true names = Split(email, "@") if UBound(names) <> 1 then IsValidEmail = false exit function end if for each name in names if Len(name) <= 0 then IsValidEmail = false exit function end if for i = 1 to Len(name) c = Lcase(Mid(name, i, 1)) if InStr("abcdefghijklmnopqrstuvwxyz_-.", c) <= 0 and not IsNumeric(c) then IsValidEmail = false exit function end if next if Left(name, 1) = "." or Right(name, 1) = "." then IsValidEmail = false exit function end if next if InStr(names(1), ".") <= 0 then IsValidEmail = false exit function end if i = Len(names(1)) - InStrRev(names(1), ".") if i <> 2 and i <> 3 then IsValidEmail = false exit function end if if InStr(email, "..") > 0 then IsValidEmail = false end if end function%>
?