V
V
Vlad2021-05-22 18:11:42
JavaScript
Vlad, 2021-05-22 18:11:42

JavaScript. How to write this validation nicely?

How to write this validation nicely?

function testBtn(e) {
    const { target } = e;
    if (target.id !== "btn") {
        return;
    }
    // валидация
    const n = prompt("Число?");
    if (n === null) {
        return;
    } else if (n.trim() === "") {
        alert("Вы ничего не ввели");
        return;
    } else if (isNaN(n)) {
        alert("Введите число");
        return;
    } else if (parseInt(n) < 1) {
        p.textContent = `Ноль или меньше: ${Number(n)}`;
        return;
    } else if (parseInt(n) > 0) {
        p.textContent = `Больше нуля ${Number(n)}`;
        return;
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
wakenby, 2021-05-22
@onndes

function testBtn(event) {
  if (event.target.id !== 'btn') return

  let answer = prompt('Число?')

  if (answer === null) return
  if (answer.trim() === '') return alert('Вы ничего не ввели')
  if (!isNumeric(answer)) return alert('Введите число')

  answer = Number(answer)

  if (answer < 1) console.log(`Меньше единицы: ${answer}`)
  else if (answer > 0) console.log(`Больше нуля: ${answer}`)

  function isNumeric (n) {
    return !isNaN(parseFloat(n)) && isFinite(n)
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question