Nishaglobal Education logo

Reading form input and validating it

Read text boxes, numbers, drop-downs, checkboxes and radio buttons with JavaScript, convert and check the values, and show clear, accessible error messages before using them.

Lesson 10 of 1340 minQuiz: 4 questions

🎯 By the end of this lesson you will be able to:

  • Read values from every common form control
  • Convert and validate input, and show helpful error messages
  • Build a small calculator that updates as people change the form
Outline
  1. What you'll learn and why it matters
  2. Reading each kind of control
  3. Checking input before using it
  4. Updating results as the form changes
  5. Practice
  6. Common mistakes
  7. Recap
  8. Quiz
  9. Mark lesson complete

What you'll learn and why it matters

Forms are how people talk to your app: orders, bookings, searches, sign-ups. In the HTML & CSS course you built forms; now you will use what people type. The golden rule: never trust input. People leave boxes empty, type letters into number fields and add spaces by accident. Good code checks first and explains clearly what to fix.

Reading each kind of control

ControlRead withGives you
Text, email, textareainput.valueA string (maybe empty)
NumberNumber(input.value) or input.valueAsNumberA number, or NaN if empty or invalid
Select (drop-down)select.valueThe chosen option's value string
Checkboxcheckbox.checkedtrue or false
Radio groupform.querySelector('input[name="size"]:checked').valueThe chosen radio's value
JavaScript
const form = document.querySelector("#order");

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const drink = document.querySelector("#drink").value;
  const cups = Number(document.querySelector("#cups").value);
  const size = form.querySelector('input[name="size"]:checked').value;
  const takeaway = document.querySelector("#takeaway").checked;

  console.log(drink, cups, size, takeaway);
  console.log(typeof cups);
});

Console (Chrome and Edge)

chai 2 regular false
number
Show the HTML and CSS this script works with

HTML

<form id="order">
  <label for="drink">Drink</label>
  <select id="drink">
    <option value="chai">Masala chai</option>
    <option value="coffee">Filter coffee</option>
  </select>
  <label for="cups">Cups</label>
  <input type="number" id="cups" value="2" min="1" max="10">
  <fieldset>
    <legend>Size</legend>
    <input type="radio" id="regular" name="size" value="regular" checked>
    <label for="regular">Regular</label>
    <input type="radio" id="large" name="size" value="large">
    <label for="large">Large</label>
  </fieldset>
  <input type="checkbox" id="takeaway">
  <label for="takeaway">Takeaway</label>
  <button type="submit">Check order</button>
</form>

CSS

.error { color: #b91c1c; font-weight: 700; }
label { display: block; margin-top: 0.5rem; }

Live preview: try it

Console

Nothing logged yet.

The console output above is what you see when you press Check order without changing anything. Change the choices in the preview and press it again: the console shows the new values. Notice the Number() conversion: without it, cups would be the string "2".

Checking input before using it

Check each value, collect a message for anything wrong, and only carry on when everything is fine. Show the message next to the field and connect it with aria-describedby, so screen readers read it with the field.

JavaScript
const form = document.querySelector("#booking");
const nameInput = document.querySelector("#guest");
const peopleInput = document.querySelector("#people");
const nameError = document.querySelector("#guest-error");
const peopleError = document.querySelector("#people-error");
const result = document.querySelector("#result");

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const name = nameInput.value.trim();
  const people = Number(peopleInput.value);

  nameError.textContent = name ? "" : "Please enter your name.";

  if (peopleInput.value === "" || Number.isNaN(people)) {
    peopleError.textContent = "Please enter how many people are coming.";
  } else if (!Number.isInteger(people) || people < 1 || people > 8) {
    peopleError.textContent = "We can seat 1 to 8 people per booking.";
  } else {
    peopleError.textContent = "";
  }

  if (nameError.textContent) {
    nameInput.focus();
  } else if (peopleError.textContent) {
    peopleInput.focus();
  } else {
    result.textContent = `Table booked for ${name}, ${people} people.`;
  }
});
Show the HTML and CSS this script works with

HTML

<form id="booking" novalidate>
  <label for="guest">Name</label>
  <input type="text" id="guest" aria-describedby="guest-error">
  <p id="guest-error" class="error"></p>
  <label for="people">Number of people</label>
  <input type="number" id="people" aria-describedby="people-error">
  <p id="people-error" class="error"></p>
  <button type="submit">Book a table</button>
</form>
<p id="result" aria-live="polite"></p>

CSS

.error { color: #b91c1c; font-weight: 700; }
label { display: block; margin-top: 0.5rem; }

Live preview: try it

Console

Nothing logged yet.

Try it in the preview: submit it empty, then with 12 people, then with 4. A few details make this form friendly:

DetailWhy
novalidate on the formTurns off the browser's own pop-up messages, so ours are the only ones (and look the same in every browser)
trim() on the nameA name of only spaces counts as empty
Number.isNaN and Number.isIntegerCatch letters, empty boxes and decimals like 2.5 people
Specific messages*We can seat 1 to 8 people* says how to fix it; *Invalid input* does not
Moving focus to the first problemKeyboard and screen-reader users land exactly where they need to fix something

Updating results as the form changes

For calculators, listen for input on an element that wraps all the fields, so any change recalculates. There is no submit button, so this one uses a <div> rather than a <form>:

JavaScript
const form = document.querySelector("#tip-form");
const output = document.querySelector("#tip-result");

function update() {
  const bill = Number(document.querySelector("#bill").value);
  const percent = Number(document.querySelector("#percent").value);

  if (!bill || bill < 0) {
    output.textContent = "Enter the bill amount.";
    return;
  }

  const tip = (bill * percent) / 100;
  output.textContent = `Tip ₹${tip.toFixed(2)}, total ₹${(bill + tip).toFixed(2)}`;
}

form.addEventListener("input", update);
update();
Show the HTML and CSS this script works with

HTML

<div id="tip-form">
  <label for="bill">Bill (₹)</label>
  <input type="number" id="bill" min="0" step="0.01">
  <label for="percent">Tip</label>
  <select id="percent">
    <option value="5">5%</option>
    <option value="10" selected>10%</option>
    <option value="15">15%</option>
  </select>
</div>
<p id="tip-result" aria-live="polite"></p>

CSS

.error { color: #b91c1c; font-weight: 700; }
label { display: block; margin-top: 0.5rem; }

Live preview: try it

Console

Nothing logged yet.

Events from a field bubble up to the elements around it, so one listener on the wrapper hears changes from every field inside. Calling update() once at the end fills in the result when the page first loads.

Practice

Guided exercise

Age checker

When the form is submitted, read the birth year. If it is empty or not between 1900 and 2026, show an error in #year-error and focus the field. Otherwise show You are about N years old. in #age (2026 minus the year).

  1. Listen for submit on the form and call preventDefault().
  2. Read Number(yearInput.value).
  3. Check yearInput.value === "", Number.isInteger, and the range.
  4. Show either the error (and focus) or the result, and clear the other.
Show the solution
Solution
const form = document.querySelector("#age-form");
const yearInput = document.querySelector("#year");
const yearError = document.querySelector("#year-error");
const ageOutput = document.querySelector("#age");

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const year = Number(yearInput.value);

  if (yearInput.value === "" || !Number.isInteger(year) || year < 1900 || year > 2026) {
    yearError.textContent = "Enter a year between 1900 and 2026.";
    ageOutput.textContent = "";
    yearInput.focus();
    return;
  }

  yearError.textContent = "";
  ageOutput.textContent = `You are about ${2026 - year} years old.`;
});
Show the HTML and CSS this script works with

HTML

<form id="age-form" novalidate>
  <label for="year">Year you were born</label>
  <input type="number" id="year" aria-describedby="year-error">
  <p id="year-error" class="error"></p>
  <button type="submit">Work out my age</button>
</form>
<p id="age" aria-live="polite"></p>

CSS

.error { color: #b91c1c; font-weight: 700; }
label { display: block; margin-top: 0.5rem; }

Live preview: try it

Console

Nothing logged yet.

How to get there: All the problem cases are checked in one condition; the early return stops the function before the result is shown. Clearing the other message each time keeps old errors or results from hanging around.

Your turn

Live unit converter

Convert kilometres to miles as the person types: show N km = M miles with 2 decimal places (1 km = 0.621371 miles), or Enter a distance. if the box is empty or not a number.

Show the solution
Solution
const km = document.querySelector("#km");
const output = document.querySelector("#miles");

km.addEventListener("input", () => {
  const value = Number(km.value);
  if (km.value === "" || Number.isNaN(value)) {
    output.textContent = "Enter a distance.";
    return;
  }
  output.textContent = `${value} km = ${(value * 0.621371).toFixed(2)} miles`;
});
Show the HTML this script works with
<label for="km">Kilometres</label>
<input type="number" id="km">
<p id="miles" aria-live="polite">Enter a distance.</p>

Live preview: try it

Console

Nothing logged yet.

How to get there: An empty box gives Number("") === 0, which looks like a real distance, so check for the empty string explicitly. toFixed(2) formats the answer.

Common mistakes

Doing maths on input.value directly

You see: Totals like "2" + "3" = "23"

Fix: Convert with Number() first.

Treating an empty number box as 0

You see: Number("") is 0, so empty boxes pass the check

Fix: Check input.value === "" before converting.

Reading values once when the page loads

You see: Your code always sees the starting values

Fix: Read .value inside the event handler, at the moment you need it.

Error messages that only use red colour

You see: Some people cannot tell that something is wrong

Fix: Use clear words, link them with aria-describedby, and move focus to the field.

Relying only on browser checks

You see: Bad data still gets through (and can be sent by tools that skip your page)

Fix: Check in JavaScript for a good experience, and on the server for safety.

Recap

  • Read .value for text, select and number boxes, .checked for checkboxes, and :checked for radio groups.
  • Everything typed is a string: convert with Number() and check for "" and NaN.
  • Show specific errors next to fields with aria-describedby, and focus the first problem.
  • Listen for input on a wrapper element to recalculate live; return early on invalid input.

Key terms

Validation
Checking that input is complete and sensible before using it.
aria-describedby
An attribute that links a field to extra text, such as an error message, for screen readers.
Event bubbling
Events on an element also reach its parents, so one listener on a wrapper can hear all the fields inside it.

Check your understanding

Answer all 4 questions, then check your answers to see an explanation for each one.

  1. 1. How do you tell if a checkbox is ticked?

  2. 2. What does `Number("")` return?

  3. 3. Why move focus to the first field with an error?

  4. 4. Why should a website also check form data on the server?

Answer all 4 questions to check.

Mark this lesson complete

Finished this lesson?

When you have worked through the examples and exercises, mark it complete to save your progress.