Answer the question
In order to leave comments, you need to log in
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
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 questionAsk a Question
731 491 924 answers to any question