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:
- The use of
===
instead of==
: see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness - The use of
||
(the logical OR) instead of|
(the bitwise OR) - Parenthesis placement helps make clear the order of operations
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") {...}