Veronica
Veronica

Reputation: 181

if condition executing for AND && in javascript, it shouldn't

This is a simple form of 3 fields and I've put condition to check for all empty.

I have given email input in run time, yet this below condition is going TRUE:

if ((inputName.value == null) && (inputEmail.value == null) && (inputDate.value == null)){
console.log('empty fields')
alert('All the fields are mandatory')
return;
}

Can anyone tell whats wrong in here?

Upvotes: 1

Views: 89

Answers (3)

libik
libik

Reputation: 23029

I see two issues.

The first is that value is probably empty string. You can use ! which handles both - empty string and null/undefined.

The second if all fields are mandatory, then any missing field should trigger the if statement, therefore you need the or, which is ||

if ((!inputName.value) || (!inputEmail.value) || (!inputDate.value)){
  console.log('empty fields')
  alert('All the fields are mandatory')
  return;
}

Also then you should start thinknig how to write it in a way that it is easily extensible. This would do the trick

    if (anyEmpty([inputName.value, inputEmail.value, inputDate.value])){
      console.log('empty fields')
      alert('All the fields are mandatory')
      return;
    }

function anyEmpty(arr) {
  arr.forEeach(str => {
    if (!str) {
      return true;
    }
  }

  return false;
}

Upvotes: 2

Sawant Sharma
Sawant Sharma

Reputation: 758

Try this, instead of null match with ''

if ((inputName.value == '') || (inputEmail.value == '') || (inputDate.value == '')){
  console.log('empty fields')
  alert('All the fields are mandatory')
  return;
}

Edit: replace && with ||

Upvotes: 2

Nicolas
Nicolas

Reputation: 8650

There is a few ways to check if a string is empty in Javascript. I like to check whether or not it's length is 0.

let inputNameNotEmpty = {value: "test"}
let inputName = {value: ""}
let inputEmail = {value: ""}
let inputDate = {value: ""}

// here, the length is 0. which, in javascript, can be evaluated as a boolean ( false in this case ). That's why we add the boolean operator ! in front of each check.
if (!inputName.value.length && !inputEmail.value.length && !inputDate.value.length){
  console.log('all empty fields')
} else {
  console.log('some fields are empty')
}

Upvotes: 1

Related Questions