Aral Code

The DOM Lesson 25 of 30

JavaScript Forms and Input Validation

Read values from inputs, selects, checkboxes and radio buttons, validate them with JavaScript, show friendly error messages, and build a BMI calculator.

Forms are how users give your page information. JavaScript can read what they typed, check if it makes sense, and respond instantly without sending anything to a server. This lesson puts together everything you've learned so far.

Reading values

Input typeHow to read it
Text, number, email, textareainput.value (always a string)
Number as a numberNumber(input.value) or input.valueAsNumber
Select menuselect.value (the selected option's value)
Checkboxcheckbox.checked (true/false)
Radio buttonsdocument.querySelector('input[name="x"]:checked').value
Example Reading every kind of input
<form id="f">
  <p><label>Name: <input id="name"></label></p>
  <p><label>Grade:
    <select id="grade"><option>7</option><option>8</option><option selected>9</option><option>10</option></select>
  </label></p>
  <p>Shift:
    <label><input type="radio" name="shift" value="Morning" checked> Morning</label>
    <label><input type="radio" name="shift" value="Afternoon"> Afternoon</label>
  </p>
  <p><label><input type="checkbox" id="club"> Join the coding club</label></p>
  <button>Submit</button>
</form>
<p id="out"></p>
<script>
  document.getElementById("f").addEventListener("submit", (e) => {
    e.preventDefault();
    const name = document.getElementById("name").value.trim() || "(no name)";
    const grade = document.getElementById("grade").value;
    const shift = document.querySelector('input[name="shift"]:checked').value;
    const club = document.getElementById("club").checked;
    document.getElementById("out").textContent =
      `${name}, Grade ${grade}, ${shift} shift, ${club ? "joining" : "not joining"} the club.`;
  });
</script>

Validation: checking the input

Never trust input blindly. Users leave boxes empty, type letters in number boxes, or make typos. Validation means checking the data and explaining what's wrong.

Example Validating a registration form
<style>
  .err { color: #b4372b; font-size: 14px; margin: 2px 0 8px; min-height: 1em; }
  input.bad { border: 2px solid #b4372b; }
</style>
<form id="reg" novalidate>
  <label>Full name<br><input id="fullname"></label>
  <p class="err" id="e-name"></p>
  <label>Age<br><input id="age" type="number"></label>
  <p class="err" id="e-age"></p>
  <label>Mobile number<br><input id="cp" placeholder="09XXXXXXXXX"></label>
  <p class="err" id="e-cp"></p>
  <button>Register</button>
</form>
<p id="ok"></p>
<script>
  function setError(inputId, errId, message) {
    document.getElementById(errId).textContent = message;
    document.getElementById(inputId).classList.toggle("bad", message !== "");
    return message === "";
  }

  document.getElementById("reg").addEventListener("submit", (e) => {
    e.preventDefault();
    const name = document.getElementById("fullname").value.trim();
    const age = Number(document.getElementById("age").value);
    const cp = document.getElementById("cp").value.trim();

    const ok1 = setError("fullname", "e-name", name.length < 2 ? "Please enter your full name." : "");
    const ok2 = setError("age", "e-age", !age || age < 10 || age > 25 ? "Age must be from 10 to 25." : "");
    const ok3 = setError("cp", "e-cp", !/^09\d{9}$/.test(cp) ? "Use 11 digits starting with 09." : "");

    document.getElementById("ok").textContent = ok1 && ok2 && ok3 ? "✅ Registered! Salamat." : "";
  });
</script>

The pattern /^09\d{9}$/ is a regular expression: a mini-language for matching text. It means "starts with 09, followed by exactly 9 digits, and nothing else". .test(text) returns true or false.

HTML validation vs. JavaScript validation

HTML can already check some things with attributes like required, min, max, type="email" and pattern (see the HTML course). JavaScript adds:

  • custom messages in your own words (and language)
  • checks that compare fields, like "passwords must match"
  • live feedback while typing

Live calculation: a BMI calculator

Example BMI calculator (updates as you type)
<label>Weight (kg) <input id="w" type="number" value="50"></label><br>
<label>Height (cm) <input id="h" type="number" value="160"></label>
<p id="bmi" style="font-size:20px"></p>
<script>
  const w = document.getElementById("w");
  const h = document.getElementById("h");

  function update() {
    const kg = Number(w.value);
    const m = Number(h.value) / 100;
    if (!kg || !m) {
      document.getElementById("bmi").textContent = "Enter your weight and height.";
      return;
    }
    const bmi = kg / (m * m);
    let label = "Normal";
    if (bmi < 18.5) label = "Underweight";
    else if (bmi >= 25) label = "Overweight";
    document.getElementById("bmi").textContent = `BMI: ${bmi.toFixed(1)} (${label})`;
  }

  w.addEventListener("input", update);
  h.addEventListener("input", update);
  update();
</script>

Getting all values at once: FormData

For bigger forms, FormData reads every field that has a name attribute:

form.addEventListener("submit", (e) => {
  e.preventDefault();
  const data = Object.fromEntries(new FormData(form));
  // data is now like { name: "Ana", grade: "9", shift: "Morning" }
});

Quick Quiz

Check what you learned. Walang grade ito, practice lang. 🙂

1. How do you check if a checkbox is ticked?
2. What type is input.value for a number input?
3. Why must data also be validated on the server?
4. What does /^09\d{9}$/.test("09171234567") return?

By Sir Reyel · Last updated 2026-12-04