我是一名新的JavaScript程序员,我正在尝试使用JavaScript创建一个表单验证程序但是如果所有表单都没有填充,那么错误消息似乎不显示,即如果所有表单都是空的,则只显示名称表单错误显示。
这就是我的尝试:
function myValidate() {
var x = document.forms["myform"]["name"].value;
var y = document.forms["myform"]["country"].value;
var z = document.forms["myform"]["occupation"].value;
var a = document.forms["myform"]["status"].value;
if (x == "null" || x == "") {
var b = document.getElementById("nameErr");
b.innerHTML = "Name Must Be Filled Out";
return false;
} else {
var b = document.getElementById("nameErr");
b.innerHTML = "";
return true;
}
if (y == "null" || y == "") {
var c = document.getElementById("countryErr");
c.innerHTML = "Country Must Be Filled Out";
return false;
} else {
var c = document.getElementById("countryErr");
c.innerHTML = "";
return true;
}
if (z == "null" || z == "") {
var d = document.getElementById("occupationErr");
d.innerHTML = "Occupation Must Be Filled Out";
return false;
} else {
var d = document.getElementById("occupationErr");
d.innerHTML = "";
return true;
}
if (a == "null" || a == "") {
var e = document.getElementById("statusErr");
e.innerHTML = "Status Must Be Filled Out";
return false;
} else {
var e = document.getElementById("statusErr");
e.innerHTML = "";
return true;
}
}
这是JavaScript代码。
<form action="process.php" method="post" onsubmit="return myValidate()" name="myform">
Name:
<input type="text" id="name" name="name">
<span id="nameErr"></span><br><br>
Country:
<input type="text" id="country" name="country">
<span id="countryErr"></span><br><br>
Occupation:
<input type="text" id="occupation" name="occupation">
<span id="occupationErr"></span><br><br>
Status:
<input type="text" id="status" name="status">
<span id="statusErr"></span><br><br>
<input type="submit" name="submit" value="Submit">
</form>
这是HTML表单。
请帮忙,谢谢
答案 0 :(得分:1)
您似乎没有意识到调用return
会结束您所处的功能。如果验证失败,您需要return false
,但您不想return true
}直到验证过程结束。
尝试:
function myValidate() {
var x = document.forms["myform"]["name"].value;
var y = document.forms["myform"]["country"].value;
var z = document.forms["myform"]["occupation"].value;
var a = document.forms["myform"]["status"].value;
var b = document.getElementById("nameErr");
var c = document.getElementById("countryErr");
var d = document.getElementById("occupationErr");
var e = document.getElementById("statusErr");
if (!x || x.length==0) {
b.innerHTML = "Name Must Be Filled Out";
return false;
} else {
b.innerHTML = "";
}
if (!y || y.length==0) {
c.innerHTML = "Country Must Be Filled Out";
return false;
} else {
c.innerHTML = "";
}
if (!z || z.length==0) {
d.innerHTML = "Occupation Must Be Filled Out";
return false;
} else {
d.innerHTML = "";
}
if (!a || a.length==0) {
e.innerHTML = "Status Must Be Filled Out";
return false;
} else {
e.innerHTML = "";
}
return true;
}
这将返回它遇到的第一个错误。如果您想一次性检查所有内容,则需要将您的true / false存储在变量中并暂停所有return
次调用,然后结束并致电return theVariableName;
答案 1 :(得分:-1)