если условие выполняется для AND && в JavaScript, оно не должно - PullRequest
1 голос
/ 11 октября 2019

Это простая форма из 3 полей, и я поставил условие, чтобы проверить все пустые.

Я дал адрес электронной почты во время выполнения, но это условие ниже ИСТИНА:

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

Кто-нибудь может сказать, что здесь не так?

Ответы [ 3 ]

2 голосов
/ 11 октября 2019

Я вижу две проблемы.

Во-первых, value, вероятно, пустая строка. Вы можете использовать !, который обрабатывает как пустую строку, так и null / undefined.

Второе, если все поля являются обязательными, любое пропущенное поле должно вызывать оператор if, поэтому вам нужен or, ||

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

Кроме того, вы должны начать думать о том, как написать его так, чтобы он был легко расширяемым. Это сделало бы трюк

    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;
}
2 голосов
/ 11 октября 2019

Попробуйте это вместо нулевого совпадения с ''

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

Редактировать: заменить && на ||

1 голос
/ 11 октября 2019

Есть несколько способов проверить, является ли строка пустой в Javascript. Мне нравится проверять, равна ли его длина 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')
}
...