出于某种原因,我的验证函数运行良好,直到我尝试传入从函数接收到的变量。目前以下工作正常,但是当我txtValue
在下面取消注释时它不起作用。
function validate(formName) {
// create an object array to hold all html nodes
var formNodes = formName.getElementsByTagName("*");
var formNodesLength = formNodes.length;
// placeholder for error codes
var error = "";
// error style
var borderStyle = "3px solid #bbd531";
var txtValue = "";
// loop and find all nodes with the attribute "validate"
for (x=0; x<formNodesLength; x++) {
if(formNodes[x].getAttribute("data-validation")){
nodeValue = formNodes[x].value;
nameValue = formNodes[x].getAttribute("name");
validateValue = formNodes[x].getAttribute("data-validation");
if (validateValue=="text" && (nodeValue==null || nodeValue=="")) { //if text match failed
alert(nameValue);
/*txtValue = findLabelValue();*/
error += /*txtValue + */" is required<br />";
formNodes[x].style.border=borderStyle;
}
else if (validateValue=="email" && !nodeValue.match(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i)) { //if email match failed
error += "email must be a valid address<br />";
formNodes[x].style.border=borderStyle;
}
else if (validateValue=="phone" && !nodeValue.match(/\b[0-9]{3}-[0-9]{3}-[0-9]{4}\b/)) { //if phone match failed
error += "phone must be a valid<br />";
formNodes[x].style.border=borderStyle;
}
else if (validateValue=="website" && !nodeValue.match(/\b[a-zA-Z0-9\-\.]+\.[A-Z]{2,4}\b/i)) { //if website match failed
error += "website must be a valid address<br />";
formNodes[x].style.border=borderStyle;
}
}
}
if(error) {
var formElement = "<div id='error-box'><strong>There was a problem with your submission</strong><br /></div>" + formName.innerHTML;
formName.innerHTML = formElement;
document.getElementById("error-box").innerHTML = error;
return false;
}
else {
return true;
}
function findLabelValue() {
var labelTagObj = formName.getElementsByTagName("label");
var returnValue = "";
for (x=0; x<labelTagObj.length; x++) {
if (labelTagObj[x].getAttribute("for") == nameValue) {
returnValue = labelTagObj[x].innerText;
return returnValue;
}
}
} // End findLabelValue()
} // End validate(formName)