我希望用户在"email2"中验证他的电子邮件地址字段,如果他输入了错误的电子邮件地址,该函数返回一条错误消息,并从"email"中更正他的电子邮件地址。字段。此函数不返回错误,但也不工作,即当电子邮件地址不同时不报告错误消息。我在寻求帮助。
<html>
<script>
function validateForm() {
var x = document.forms["contactform"]["email"].value;
if (x == "") {
alert("E-mail is empty");
return false;
}
var x = document.forms["contactform"]["email2"].value;
if (x == "") {
alert("Verification E-mail is empty");
return false;
if(email != email2){
// Display the error message
document.getElementById("emailMismatch").style.display="inline";
alert("Email address does not match");
return false;
}else{
document.getElementById("emailMismatch").style.display="none";
}
}
}
</script>
<body>
<form name="contactform" method="post">
<input type="text" name="email" maxlength="80" size="30" placeholder="E-mail contact person" title="The e-mail must be in the format, example: primer@email.com ">
<input type="text" name="email2" maxlength="80" size="30" placeholder="Verify E-mail address" title="The e-mail must be in the format, example: primer@email.com ">
<input type="submit" value="Send" style="border:1px solid #000000">
</form>
</body>
</html>
您缺少}
来终止第二个IF,因此第三个IF在第二个IF内,因此永远不会运行,因为它是在返回之后:)
<script>
function validateForm() {
var x = document.forms["contactform"]["email"].value;
if (x == "") {
alert("E-mail is empty");
return false;
}
var x = document.forms["contactform"]["email2"].value;
if (x == "") {
alert("Verification E-mail is empty");
return false;
} <-- !!!!!!!!!!!!! THIS WAS MISSING !!!!!!!!!!!!
if(email != email2){
// Display the error message
document.getElementById("emailMismatch").style.display="inline";
alert("Email address does not match");
return false;
}else{
document.getElementById("emailMismatch").style.display="none";
}
#} <-- THIS WAS IN THE WRONG PLACE REMOVE IT
}
</script>
您定义了一个名为x的变量来保存电子邮件输入值,然后与未定义的email和email2变量进行比较。
function validateForm() {
var email = document.forms["contactform"]["email"].value;
if (email == "") {
alert("E-mail is empty");
return false;
}
var verificationEmail = document.forms["contactform"]["email2"].value;
if (verificationEmail == "") {
alert("Verification E-mail is empty");
return false;
} <-- !!!!!!!!!!!!! THIS WAS MISSING !!!!!!!!!!!!
if(email != verificationEmail){
// Display the error message
document.getElementById("emailMismatch").style.display="inline";
alert("Email address does not match");
return false;
}else{
document.getElementById("emailMismatch").style.display="none";
}
}