TExcelTAD
Home › JavaScript › DOM Forms & Validation

DOM Forms & Validation

Forms are how users send data: sign-ups, searches, checkouts, settings. JavaScript lets you read form values, react while the user types, and validate input before it's submitted — giving instant, friendly feedback instead of a server error after the fact.

Reading form values

Control Read with
<input type="text">, <textarea>, <select> .value (always a string)
<input type="number">, type="range" .value or .valueAsNumber
<input type="checkbox"> .checked (boolean)
radio group form.elements.groupName.value or querySelector(":checked")
whole form new FormData(form)
html · try it yourself
<form id="order">
  <p><label>Name <input name="name" value="Kim"></label></p>
  <p><label>Quantity <input name="qty" type="number" value="2" min="1" max="10"></label></p>
  <p><label>Size
    <select name="size"><option>S</option><option selected>M</option><option>L</option></select>
  </label></p>
  <p>
    <label><input type="radio" name="color" value="black" checked> Black</label>
    <label><input type="radio" name="color" value="white"> White</label>
  </p>
  <p><label><input type="checkbox" name="gift"> Gift wrap</label></p>
  <button>Order</button>
</form>
<script>
  const form = document.getElementById("order");
  form.addEventListener("submit", (e) => {
    e.preventDefault();                          // stay on the page

    const els = form.elements;
    console.log("name:", els.name.value);
    console.log("qty:", els.qty.valueAsNumber, typeof els.qty.valueAsNumber);
    console.log("size:", els.size.value, "color:", els.color.value, "gift:", els.gift.checked);

    const data = Object.fromEntries(new FormData(form));
    console.log("FormData:", data);              // unchecked checkboxes are omitted
  });
</script>

Note: Always call event.preventDefault() in a submit handler when you handle the data with JavaScript; otherwise the browser submits the form and reloads (or navigates away from) the page.

Reacting as the user types

The input event fires on every change; change fires when the user commits a value (for text fields: when they leave the field):

html · try it yourself
<label>Message (max 40 chars)<br><textarea id="msg" rows="3" cols="40"></textarea></label>
<p id="counter">0 / 40</p>
<script>
  const msg = document.getElementById("msg");
  const counter = document.getElementById("counter");
  msg.addEventListener("input", () => {
    const len = msg.value.length;
    counter.textContent = `${len} / 40`;
    counter.style.color = len > 40 ? "crimson" : "";
  });
  msg.addEventListener("change", () => console.log("committed:", JSON.stringify(msg.value)));
</script>

Built-in HTML validation

HTML attributes give you validation for free: required, type="email", min/max, minlength/maxlength, pattern. The browser blocks submission and shows a message if a rule fails, and CSS can style :invalid fields:

html · try it yourself
<style>
  input:user-invalid { border: 2px solid crimson; }
  input:valid { border: 2px solid seagreen; }
</style>
<form id="signup">
  <p><input name="email" type="email" required placeholder="Email"></p>
  <p><input name="age" type="number" min="13" max="120" required placeholder="Age"></p>
  <p><input name="zip" pattern="\d{5}" title="Five digits" placeholder="ZIP (5 digits)"></p>
  <button>Sign up</button>
</form>
<script>
  document.getElementById("signup").addEventListener("submit", (e) => {
    e.preventDefault();             // only runs when all built-in rules pass
    console.log("valid!", Object.fromEntries(new FormData(e.target)));
  });
</script>

From JavaScript you can query the same rules: input.checkValidity(), input.validity.valueMissing, input.validationMessage, and set custom messages with input.setCustomValidity("…").

Custom validation with JavaScript

Some rules can't be expressed in HTML — "passwords must match", "username not taken", "end date after start date". A common approach: add novalidate to the form, run your own checks on submit, and show messages next to each field:

html · try it yourself
<style>
  .field { margin: 8px 0; }
  .error { color: crimson; font-size: .9em; min-height: 1.2em; }
  input.bad { border: 2px solid crimson; }
</style>
<form id="register" novalidate>
  <div class="field"><input name="username" placeholder="Username"><div class="error"></div></div>
  <div class="field"><input name="password" type="password" placeholder="Password"><div class="error"></div></div>
  <div class="field"><input name="confirm" type="password" placeholder="Repeat password"><div class="error"></div></div>
  <button>Create account</button>
  <p id="result"></p>
</form>
<script>
  const form = document.getElementById("register");

  const rules = {
    username: (v) => (v.trim().length < 3 ? "At least 3 characters" : /\s/.test(v) ? "No spaces allowed" : ""),
    password: (v) => (v.length < 8 ? "At least 8 characters" : !/\d/.test(v) ? "Include a number" : ""),
    confirm: (v, all) => (v !== all.password ? "Passwords don't match" : ""),
  };

  function validate() {
    const values = Object.fromEntries(new FormData(form));
    let ok = true;
    for (const [name, check] of Object.entries(rules)) {
      const input = form.elements[name];
      const message = check(values[name], values);
      input.classList.toggle("bad", message !== "");
      input.nextElementSibling.textContent = message;
      if (message) ok = false;
    }
    return ok;
  }

  form.addEventListener("submit", (e) => {
    e.preventDefault();
    const ok = validate();
    document.getElementById("result").textContent = ok ? "✔ Account created" : "";
    if (!ok) form.querySelector(".bad")?.focus();      // jump to the first problem
  });

  // after the first attempt, re-validate live while typing
  form.addEventListener("input", () => {
    if (form.querySelector(".bad")) validate();
  });
</script>

Validation tips

  • Validate on submit, then live after the first error — validating while someone is still typing their first character feels hostile.
  • Put the message next to the field and say how to fix it ("At least 8 characters"), not just "Invalid".
  • Move focus to the first invalid field.
  • Always validate again on the server. Client-side checks are for user experience; anyone can bypass them.

Test yourself

What type is input.value for an <input type="number">?

  1. number
  2. string
  3. bigint
  4. It depends on the content

How do you read whether a checkbox is ticked?

  1. checkbox.value
  2. checkbox.checked
  3. checkbox.selected
  4. checkbox.on

Why must you still validate data on the server?

  1. Browsers don't support validation
  2. Client-side checks can be bypassed
  3. JavaScript validation is slower
  4. FormData doesn't work without a server