如何同时执行所有 IF语句?我想在RETURN之前检查所有IF,并在document.getElementById(' td100')。innerHTML中显示所有消息。
例如:如果我填写表格:
如何在(td100)中显示所有错误?
function regValidation()
{
document.getElementById('td100').innerHTML = "";
event.preventDefault ? event.preventDefault() : event.returnValue = false;
var email1 = document.getElementById('em100').value;
var email2 = document.getElementById('em101').value;
var pass1 = document.getElementById('pw100').value;
var pass2 = document.getElementById('pw101').value;
if (!document.getElementById('em100').checkValidity()) return document.getElementById('td100').innerHTML += "</br>Emails are not valid.";
if (email1 !== email2) return document.getElementById('td100').innerHTML += "</br>Emails do not match.";
if (pass1 !== pass2) return document.getElementById('td100').innerHTML += "</br>Passwords do not match.";
if (pass1.length < @minPass || pass1.length > @maxPass) return document.getElementById('td100').innerHTML += "</br>Password must be @minPass - @maxPass characters.";
return true && regSuccess();
}
答案 0 :(得分:0)
function regValidation()
{
document.getElementById('td100').innerHTML = "";
event.preventDefault ? event.preventDefault() : event.returnValue = false;
var error = "";
var email1 = document.getElementById('em100').value;
var email2 = document.getElementById('em101').value;
var pass1 = document.getElementById('pw100').value;
var pass2 = document.getElementById('pw101').value;
if (!document.getElementById('em100').checkValidity()) error += "</br>Emails are not valid.";
if (email1 !== email2) error += "</br>Emails do not match.";
if (pass1 !== pass2) error += "</br>Passwords do not match.";
if (pass1.length < @minPass || pass1.length > @maxPass) error += "</br>Password must be @minPass - @maxPass characters.";
if (error !== "")
{
document.getElementById('td100').innerHTML = error
} else {
return true && regSuccess();
}
}
答案 1 :(得分:0)
好的,现在是非常干燥的解决方案。设置一个表并迭代它:
var checks = [
[pass1===pass2,"password missmatch"],
[email1===email2,"email missmatch"]
//..
];
var passed = true;
var errors=[];
for(let [check,message] of checks){
if(!check){
alert(message)//show message
//or collect:
errors.push(message);
passed = false;
}
}
//now passed contains the result:
if(passed)
alert("wohoo, all fine ;)");
//and errors can be shown:
document.getElementById("err")
.innerHTML=errors.join("<br>");