//js代码
function validForm(){
var allGood = true;
var allTags = document.getElementsByTagName("*");
for(var i=0; i<allTags.length; i++){
if(allTags[i].nodeName=="INPUT" || allTags[i].nodeName=="TEXTAREA"){
if(!validTag(allTags[i])){
allGood=false;
}
}
}
return allGood;
function validTag(thisTag){
var outClass = "";
var allClasses = thisTag.className.split(" ");
for(var j=0; j<allClasses.length; j++){
outClass += validBasedOnClass(allClasses[j]) + " ";
}
thisTag.className = outClass;
if(outClass.indexOf("invalid") > -1){
thisTag.focus();
if(thisTag.nodeName=="INPUT"){
thisTag.select();
}
return false;
}
return true;
function validBasedOnClass(thisClass){
var classBack = "";
switch(thisClass){
case "":
case "invalid":break;
case "reqd":
if(allGood && thisTag.value=="") classBack = "invalid ";
classBack += thisClass;
break;
case "pwd":
if(allGood && !crossCheck(thisTag,thisClass)) classBack = "invalid ";
classBack += thisClass;
break;
default:
classBack += thisClass;
}
return classBack
}
function crossCheck(inTag,otherFieldId){
var inTagValue = inTag.value;
var otherFieldValue = document.getElementById(otherFieldId);
return (inTagValue==otherFieldValue);
}
}
}
//css 代码
.invalid {
background-color: #ff9;
border: 2px red inset;
}
//页面使用,在class里面添加reqd就 可以了,记得 和其他的class分开
<input id="userid" name="username" size="25" maxlength="25" type="text" class="reqd">