フォーム検証の原理
7911 ワード
<form action="#">
<p><label for="userName">Your name:<input type="text" size="30" id="userName" class="reqd">label> p>
<p><label for="passwd1">Choose a password: <input type="password" id="passwd1" class="reqd">label>p>
<p><label for="passwd2">Verify password:<input type="password" id="passwd2" class="reqd passwd1">
label>p>
<p><input type="submit" value="Submit"> <input type="reset">p>
form>
フォームスタイルのコントロールを不正に送信します.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; i< document.forms.length;i++) {
document.forms[i].onsubmit = validForm;
}
}
function validForm() {
var allGood = true;
var allTags = document.getElementsByTagName("*");
for (var i=0; iif (!validTag(allTags[i])) {
allGood = false;
}
}
return allGood;
}
function validTag(thisTag) {
var outClass = "";
var allClasses = thisTag.className. split(" ");
for (var j=0; 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;
default:
classBack += thisClass;
}
return classBack;
}