名字、姓氏和电子邮件地址的 JavaScript 表单验证不显示任何内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23145277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript form validation for first name, last name and email address is displaying nothing
提问by Acemi
I am just copying my code:
我只是复制我的代码:
HTML
HTML
<form id='test'>
Name *
<input id="lname" type="text"><span id="wronglname" class="error">*This is a required field</span>
Name *
<input id="name" type="text"><span id="wrongname" class="error">*This is a required field</span>
Email*
<input id="email" type="text"><span id="wrongemail" class="error">* Wrong Email Address</span>
<div>
<input type="submit" value="Submit">
</div>
</form>
Javascript
Javascript
function ValidateForm() {
var hasError = false;
if (document.getElementById('lname').value == "") {
document.getElementById('lwrongname').style.display = "inline";
hasError = true;
} else {
document.getElementById('wrongname').style.display = "none";
}
if (document.getElementById('name').value == "") {
document.getElementById('wrongname').style.display = "inline";
hasError = true;
} else {
document.getElementById('wrongname').style.display = "none";
}
if (document.getElementById('email').value.search(/^[a-zA-Z]+([_\.-]?[a-zA-Z0-9]+)*@[a-zA-Z0-9]+([\.-]?[a-zA-Z0-9]+)*(\.[a-zA-Z]{2,4})+$/) == -1) {
document.getElementById('wrongemail').style.display = "inline";
hasError = true;
} else {
document.getElementById('wrongemail').style.display = "none";
}
return !hasError;
}
document.getElementById('test').onsubmit = ValidateForm;
CSS
CSS
.error {
display:none;
color:red;
}
I am getting no response at all, and whenever I check javascript console by chrome, it shows me also no error, I am not too sure what's wrong with my coding, can anyone help me out?
我根本没有得到任何回应,每当我通过 chrome 检查 javascript 控制台时,它也显示我没有错误,我不太确定我的编码有什么问题,有人能帮我吗?
回答by Sunyatasattva
Here is your mistake:
这是你的错误:
if (document.getElementById('lname').value == "") {
document.getElementById('lwrongname').style.display = "inline";
hasError = true;
}
Notice document.getElementById('lwrongname')
, should be document.getElementById('wronglname')
.
注意document.getElementById('lwrongname')
,应该是document.getElementById('wronglname')
。