【封装为表单验证的专用js,所有表单页面都可以调用】
1、表单
<form id="regForm" method="post" action="index/register" onsubmit="checkForm(this)"> .... <td><label class="ui-green"><input type="submit" name="submit" value="提交注册" /></label></td>
2、验证form表单
function checkForm(frm) { var els = frm.getElementsByTagName("input"); for(var i=0; i<els.length; i++) { if(typeof(els[i].getAttribute("onblur")) == "function") { if(!CheckItem(els[i])) return false; } } return true; }
3、验证该表单下的所有input框
function CheckItem(obj) { //将input提示框的内容赋空 obj.parentNode.parentNode.className = ""; var msgBox = obj.parentNode.getElementsByTagName("span")[0]; switch(obj.name) { case "regUserName": //这后面的业务可以单独提出来作为一个方法 if(obj.value == "") { msgBox.innerHTML = "密码不能为空!"; //添加className方便统一管理样式 msgBox.className = "error"; return false; }else{ //用户名被占用 $.ajax({ "url":"index/hasname", "data":"username="+obj.value, "type":"post", "dataType":"json", "success":function(data){ if(data=="1"){ msgBox.innerHTML = "用户名已存在!"; msgBox.className = "error"; return false; }else{ //用户名可用 msgBox.innerHTML = "用户名可用!"; msgBox.className = "nameinfo"; } } }); } break; case "userName": if(obj.value == "") { msgBox.innerHTML = "密码不能为空!"; msgBox.className = "error"; return false; } break; case "passWord": if(obj.value == "") { msgBox.innerHTML = "密码不能为空!"; msgBox.className = "error"; return false; } break; case "rePassWord": if(obj.value == "") { msgBox.innerHTML = "密码不能为空!"; msgBox.className = "error"; return false; } else if(obj.value != document.getElementById("passWord").value) { msgBox.innerHTML = "两次密码不一致!"; msgBox.className = "error"; return false; } break; case "veryCode": if(obj.value == "") { msgBox.innerHTML = "验证码不能为空!"; msgBox.className = "error"; return false; } break; } return true; }