我有一个函数可以检查字段是否为空,但如果所有字段都为空,它只显示其中一条验证消息,我认为这是因为我使用了 if 语句:
function validateForm()
{
var sName=document.forms["myForm"]["surname_5"].value;
if (sName==null || sName=="")
{
document.getElementById("sNameMessage").innerHTML = "*Surname is required";
return false;
}
var x=document.forms["myForm"]["firstname_4"].value;
if (x==null || x=="")
{
document.getElementById("fNameMessage").innerHTML = "*First name is required";
return false;
}
var y=document.forms["myForm"]["selectid"];
if(y.options[y.selectedIndex].value == "Title")
{
document.getElementById("titleMessage").innerHTML = "You need to select a title";
return false;
}
}
如果用户将所有字段留空,如何获取它以便显示所有验证消息?
最佳答案
不要立即返回false
。将变量设置为 false
(在函数开头将其定义为 true
后)并在末尾返回该变量。
关于javascript - 使用 JavaScript 进行验证 - 如何向所有验证错误消息显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22457554/