There is proberly a simple answer to this and a more elegant than i have. I have a login form in html. You can login with your ID or your Firstname, Lastname and email. In JS i want to validate the form, i want to see if the ID field is filled or all 3 of the other fields.
这里有一个简单的答案,而且比我更优雅。我有一个html的登录表单。您可以使用您的ID或您的Firstname、Lastname和email登录。在JS中,我想验证表单,我想看看ID字段是否被填充,或者其他三个字段是否都被填满。
Here is a turth table of this: Truth table: a∨(b∧c∧d)
这是蒙在鼓里表:真值表:∨(b∧c∧d)
HTML:
HTML:
<form onsubmit="return FormValidation()" name="login" method="POST">
ID: <input type="text" name="id"><br>
<p> or </p>
Firstname: <input type="text" name="first"><br>
Lastname: <input type="text" name="last"><br>
Birthdate: <input type="date" name="birthdate"><br>
</form>
JS:
JS:
function FormValidation(){
var id = document.forms["login"]["id"].value;
var firstname = document.forms["login"]["firstname"].value;
var lastname = document.forms["login"]["lastname"].value;
var birthdate = document.forms["login"]["birthdate"].value;
if (id == "" && (firstname == "" && lastname == "" && birthdate =="")) {
alert("Something is missing");
return false;
} else if (id != "" && (firstname == "" && lastname == "" && birthdate =="")) {
alert("Ok");
return true;
} else if (id == "" && (firstname != "" && lastname != "" && birthdate !="")) {
alert("Ok");
return true;
} else if (id != "" && (firstname != "" && lastname != "" && birthdate !="")) {
alert("Ok");
return true;
} else if .....
.....
}
There are for every error a if statement.
每个错误都有一个if语句。
Please show me a more elegant way than this..
请给我一个比这个更优雅的方式。
1 个解决方案
#1
1
You may be overcomplicating this with if statements. Using logical notation maps to JavaScript quite nicely - no need to build out the truth table.
如果你说的话可能会使这个问题复杂化。使用逻辑符号映射到JavaScript很好——不需要构建真值表。
var hasId = id != "";
var hasFirstLastAndBirthday = firstname != "" && lastname != "" && birthday != "";
return hasId || hasFirstLastAndBirthday;
#1
1
You may be overcomplicating this with if statements. Using logical notation maps to JavaScript quite nicely - no need to build out the truth table.
如果你说的话可能会使这个问题复杂化。使用逻辑符号映射到JavaScript很好——不需要构建真值表。
var hasId = id != "";
var hasFirstLastAndBirthday = firstname != "" && lastname != "" && birthday != "";
return hasId || hasFirstLastAndBirthday;