0

HTML+JS My Form Validator function doing the exact opposite of its purpose?

i have created a simple JS function to validate the first name and the last name fields to make sure both are filled when submitting the form so i set up a test alert that -by my knowledge- should pop up if either first name or last name is empty or both. but the alert is only popping up when there are strings in the fields for some reason

function validateForm() {
  let x = document.forms["myForm"]["fname"].value;
  let y = document.forms["myForm"]["flname"].value;
  if ((x || y) || (X & Y) != 0) {
    alert('TEST')
    return false;
  }
}

and the HTML

<div class="form-group"><button type="button" class="btn btn-success" id="submitForm" onclick="validateForm()"
        ;>Submit</button></div>
Chris Barr
  • 29,851
  • 23
  • 95
  • 135
SamOps
  • 3
  • 2
  • `(x || y)` — if either of these are truthy; `X & Y` — neither of those are defined, and `&` is bitwise AND, not logical. You want `if (!(x && y))`, or `if (!x && !y)`, plus probably a `trim` to ensure it's not just whitespace. Or the `required` attribute. – Zac Anger May 26 '23 at 13:18
  • you are using both `x` and `y` lowercase variables and then `X` and `Y` uppercase variables. Is this intended? – Chris Barr May 26 '23 at 13:18

1 Answers1

1

As pointed out you are using x, y, X, and Y variables, but only two of them are defined in your code sample. I'm going to assume that's a typo and they all should be lowercase.

Next, you are using a single & which I assume is another typo since && is what you need to be using here as you are not using bitwise operations here

With that set aside though, let's fix that to look like this:

(x || y) || (x && y) != 0

the logic you have in your if statement is pretty wild! That says "if either x or y are true OR both x and y are both true - then you check if they are not equal to zero.

To me this makes no sense. You are just checking if a text field is filled in or not. Since x and y are strings just check if either one is empty.

x === '' || y === ''

If either is empty then continue so you can return false and prevent form submission.

function validateForm() {
  let x = document.forms["myForm"]["fname"].value;
  let y = document.forms["myForm"]["flname"].value;
  
  console.log(x, y)
  
  if (x === '' || y === '') {
    console.log('TEST')
    return false;
  }
}
<form name="myForm">
  <input type="text" name="fname">
  <input type="text" name="flname">
</form>

<button type="button" class="btn btn-success" id="submitForm" onclick="validateForm()">Submit</button>
Chris Barr
  • 29,851
  • 23
  • 95
  • 135