Checking a Form
People make mistakes: they leave a field empty, type a space before their name, or a word where a number belongs. Before a page uses what was typed into a form, its script checks it, and when something is wrong, it says what, right next to the field.
Start with trim(). It returns the text without the spaces at its start and end; the spaces inside stay:
const name = " Anna Smith ".trim();
console.log(`[${name}]`);[Anna Smith]A field with nothing but spaces in it then gives "", so a check for an empty field catches it too. Next, you can check how long the text is, with length. Each field has a place for its error message next to it, for example <span id="nick-error"></span> (a span is a piece of text inside a line, here right after the field), and the handler fills it in, or empties it when the field is right:
form.addEventListener("submit", function (event) {
event.preventDefault();
const nick = nickInput.value.trim();
if (nick === "") {
nickError.textContent = "Enter a nickname.";
} else if (nick.length < 3) {
nickError.textContent = "The nickname needs at least 3 characters.";
} else {
nickError.textContent = "";
result.textContent = `Hi, ${nick}!`;
}
});Emptying the message matters: without it, the error would stay on the page even after the user fixed the field.
Numbers. Number() turns text that isn't a number into NaN, and you can't find that with ===. NaN isn't equal to anything, not even to itself, so age === NaN is always false. Use Number.isNaN(age), which is true when age is NaN. Comparisons with NaN are always false too: NaN < 1 is false, so a check like age < 1 lets NaN through. And remember that an empty field gives Number(""), which is 0.
Several fields. A good form shows all its problems at once, not one at a time. So check every field, and remember in a variable whether something was wrong:
let valid = true;
if (nick === "") {
nickError.textContent = "Enter a nickname.";
valid = false;
} else {
nickError.textContent = "";
}
if (Number.isNaN(age) || age < 1) {
ageError.textContent = "Enter your age.";
valid = false;
} else {
ageError.textContent = "";
}
if (valid) {
result.textContent = `Hi, ${nick}!`;
}Only when every field is right does the form do its job.
Instructions
Trim the name. When it's empty, show Enter your name. in nameError; otherwise, empty nameError. Try sending the form with only spaces in the name.
Check the number of tickets. When it isn't a number, or it's less than 1 or more than 10, show Enter a number from 1 to 10. in ticketsError; otherwise, empty it.
Show the booking in result only when both fields are right, with the trimmed name: Tickets booked for Anna: 2. Otherwise, empty result. When both fields are wrong, both messages show at once.