我的大部分代码都是为它完成的,但出于某种原因,它只是在没有做任何事情的情况下提交我的表单。我试图验证SSN是否在没有破折号的情况下输入SSN。除了验证它我想改变输入的单词和背景的颜色,如果它是无效的。我已经正确设置了我的班级名称和ID,并且在我的css中我使用了input.invalid,label.invalid等颜色更改等内容。这是我的JS代码。任何帮助都会很棒,谢谢!
window.onload = function () {
document.forms[0].onsubmit = validForm;
}
function validForm () {
var allTags = document.forms[0].getElementsByTagName("*");
for(vari = 0; i < allTags.length; i++) {
validTag(allTags[i]);
}
return false;
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) {
invalidLabel(thisTag.parentNode);
thisTag.focus();
if(thisTag.nodeName == "INPUT") {
thisTag.select();
}
}
function validBasedOnClass(thisClass) {
var classBack = "";
switch(thisClass) {
case "":
case "invalid":
break;
case "Social":
if(!validSocial(thisTag.value)) {
document.getElementById("socialNum").className = ("invalid");
document.getElementById("ssn").className = ("invalid");
classBack = "invalid ";
}
break;
default:
classBack += thisClass;
}
return classBack;
}
function validSocial(social) {
var re = /^\d{3}-?\d{2}-?\d{4}$/;
var socialArray = re.test(social);
if(socialArray) {
document.getElementById("socialNum").value = socialArray[1] + "-" + socialArray[2] + "-" + socialArray[3];
return true;
}
return false;
}
function invalidLabel(parentTag) {
if(parentTag.nodeName == "LABEL") {
parentTag.className += "invalid";
}
}
}
}
这是我要求的html代码
<!DOCTYPE html>
<link rel="stylesheet" type="text/css" href="regex.css"/>
<script type="text/javascript" src="regex.js"></script>
<title>COP2831: Chapter 7 - Regular Expressions</title>
<h1>Regular Expressions - Kevin Taylor</h1>
<form>
<label for="socialNum" id="ssn">Enter Social Security Number:
<input type="text" name="Social" id="socialNum" class="Social" maxlength="9"/>
</label>
<p><input type="submit" value="Submit"> <input type="reset"></p>
</form>
答案 0 :(得分:0)
由于您的样本不完整,我不明白为什么这样做,我只是给出了SSN验证的简化工作样本。
window.onload = function () {
document.forms[0].onsubmit = validForm;
};
function validForm() {
var ssnTag = document.getElementById("socialNum");
var re = /^\d{3}-?\d{2}-?\d{4}$/;
var valid = re.test(ssnTag.value);
if (valid) {
ssnTag.style.borderColor = "green";
} else {
ssnTag.style.borderColor = "red";
}
return false;
}