Home > Back-end >  How to have 3 condition inside if statement for user input JavaScript
How to have 3 condition inside if statement for user input JavaScript

Time:10-27

JavaScript: I want to check if the user input meets 3 conditions on an if statement. I don't know how to make && and | work on a single if statement. I have the | after the first condition but the && is not taken into consideration and I can leave the input box empty and it will still redirect me to the page. I tried multiple ways but I did not get it to work. Please help and thank you in advance.

JavaScript

    function valForm() {
          var firstVal = document.getElementById("nextId").value;
          var secondVal = document.getElementById("licenseId").value;
          if (
            (firstVal == "MB3804") | (firstVal == "mb3804") &&
            (secondVal.length == 6) | 7
          ) {
            window.location.href = "google.com";
          }
        }
        

HTML

      <input
          type="text"
          placeholder="License Plate"
          id="licensed"
          autocomplete="off"
      />
      <input
          type="text"
          placeholder="Ticket ID"
          id="nextId"
          autocomplete="off"
      />
      <button class="btn btn-primary display-4" type="button" onclick="valForm()">next</button>
        

CodePudding user response:

if (
    (firstVal == "MB3804") | (firstVal == "mb3804") &&
    (secondVal.length == 6) | 7
)

should probably be

if (
    (firstVal === "MB3804" || firstVal == "mb3804") &&
    (secondVal.length === 6 || secondVal.length === 7)
)

There are few things to notice here:

paulsm's comment above is also quite valid and you could use a case-insensitive string comparison instead of 2 separate comparisons if that makes sense in your case. Of course if you want the condition to succeed for MB3804 and mb3804 but fail for Mb3804 and mB3804, then the case-insensitive string comparison will not be appropriate, but if all four cases are considered "good" then it makes a lot of sense and

if (firstVal === "MB3804" || firstVal === "mb3804") {...}

could be rewritten as

if (firstVal.toLowerCase() === "mb3804") {...}
  • Related