Search code examples
javascripthtmlformsvalidationtruthtable

Javascript: form validation with a∨(b∧c∧d)


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.

Here is a turth table of this: Truth table: a∨(b∧c∧d)

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:

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.

Please show me a more elegant way than this..


Solution

  • You may be overcomplicating this with if statements. Using logical notation maps to JavaScript quite nicely - no need to build out the truth table.

    var hasId = id != "";
    var hasFirstLastAndBirthday = firstname != "" && lastname != "" && birthday != "";
    
    return hasId || hasFirstLastAndBirthday;