=>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>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>表单验证_密码验证</title>
<link type="text/css" rel="stylesheet" href="formCheck.css" />
<script type="text/javascript" src="formCheck.js"></script>
</head>
<body>
<form action="#">
<p><label for="userName">YourName:<input type="text" size="35" id="userName" class="reqd" /></label></p>
<p><label for="passwd1">ChooseAPassword:<input type="password" size="28" id="passwd1" class="reqd" /></label></p>
<p><label for="passwd2">VerifyPassword:<input type="password" size="29" id="passwd2" class="reqd passwd1" /></label></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>
=>样式文件
body {
color: #000; //黑色;
background-color: #FFF; //白色;
}
input.invalid {
background-color: #FF9; //黄色;
border: 2px red inset;
}
label.invalid {
color: #F00; //红色;
font-weight: bold;
}
=>脚本文件
window.onload = initForms;
function initForms() {
for(var i=0, len=document.forms.length; i<len; i++) { // 循环页面上所有form表单;
document.forms[i].onsubmit = function() {
return validForm();
}
}
}
function validForm() {
var allGood = true; // 默认验证通过;
var allTags = document.getElementsByTagName("*");
for(var i=0; i<allTags.length; i++) { // 遍历每个表单的所有tag标签;
if(!validTag(allTags[i])) {
allGood = false;
}
}
return allGood;
/*validForm(结束;*/
function validTag(thisTag) {
var outClass = "";
var allClasses = thisTag.className.split(" ");
for(var j=0,len=allClasses.length; j<len; j++) {
outClass += validBasedOnClass(allClasses[j]) + " ";
}
thisTag.className = outClass;
// console.log(i);
// console.log(thisTag.id);
// console.log(outClass);
if(outClass.indexOf("invalid") > -1) {
thisTag.className = outClass.substring(0,7);
console.log(thisTag.className);
thisTag.focus();
if(thisTag.nodeName == "INPUT") {
thisTag.select();
}
return false;
}
return true;
/*validTag()函数结束;*/
function validBasedOnClass(thisClass) { // 只有空、reqd、passwd1;
var classBack = "";
switch(thisClass) {
case "":
case "invalid":
break;
case "reqd":
if(allGood && thisTag.value == "") {
classBack = "invalid";
}
classBack += thisClass;
break;
default:
classBack += thisClass;
}
return classBack;
}
}
}