Reading history

JavaScript Form Validation with Live Error Messages

7 min read 1 views

Learn JavaScript form validation: HTML rules, the validity object, live custom error messages, preventDefault, accessibility and a password strength checker.

A form that says “Error” only after submitting, without explaining what went wrong, frustrates everyone. Good form validation checks input as the user types, explains each problem in plain words next to the field, and moves focus to the first mistake. HTML already provides rules such as required and pattern; JavaScript lets you show friendly custom messages and add checks HTML cannot express.

In this lesson you will learn

  • Using HTML attributes for basic rules
  • Reading the validity object (the Constraint Validation API)
  • Showing messages live with the input event
  • Blocking submission with preventDefault
  • Building a password strength checker

This lesson builds on HTML Forms, JavaScript Events and Regular Expressions.

Live Validation With Custom Messages

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Live form validation</title>
  <style>
    body { font-family: sans-serif; margin: 10px; }
    label { display: block; margin-top: 8px; font-weight: bold; }
    input { font-size: 15px; padding: 6px; width: 240px; border: 2px solid #b0bec5; border-radius: 4px; }
    input.ok { border-color: #2e7d32; }
    input.bad { border-color: #c62828; }
    .msg { color: #c62828; font-size: 13px; min-height: 1.2em; margin: 2px 0; }
    button { margin-top: 8px; padding: 8px 14px; }
    #result { font-weight: bold; color: #2e7d32; }
  </style>
</head>
<body>
  <form id="signup" novalidate>
    <label for="name">Name</label>
    <input id="name" required minlength="3" aria-describedby="name-msg">
    <p id="name-msg" class="msg"></p>

    <label for="phone">Mobile (01XXXXXXXXX)</label>
    <input id="phone" required pattern="01[3-9][0-9]{8}" aria-describedby="phone-msg">
    <p id="phone-msg" class="msg"></p>

    <button type="submit">Sign up</button>
    <p id="result" role="status"></p>
  </form>
  <script>
    const form = document.getElementById("signup");
    const messages = {
      name: { valueMissing: "Please enter your name.", tooShort: "Use at least 3 letters." },
      phone: { valueMissing: "Please enter a mobile number.", patternMismatch: "Use 11 digits starting with 01." },
    };

    function check(input) {
      const msg = document.getElementById(input.id + "-msg");
      const v = input.validity;                    // the browser's built-in checks
      let text = "";
      for (const key in messages[input.id]) {
        if (v[key]) { text = messages[input.id][key]; break; }
      }
      msg.textContent = text;
      input.classList.toggle("bad", text !== "");
      input.classList.toggle("ok", text === "");
      input.setAttribute("aria-invalid", text !== "");
      return text === "";
    }

    form.addEventListener("input", e => check(e.target));
    form.addEventListener("submit", e => {
      e.preventDefault();
      const fields = [...form.querySelectorAll("input")];
      const allOk = fields.map(check).every(Boolean);
      document.getElementById("result").textContent = allOk ? "Thanks! Form is valid." : "";
      if (!allOk) fields.find(f => f.classList.contains("bad")).focus();
    });
  </script>
</body>
</html>

Result

  • The rules stay in HTML: required, minlength="3" and pattern. novalidate on the form turns off the browser’s default pop-ups so the page can show its own messages.
  • Every input has a validity object with flags such as valueMissing, tooShort and patternMismatch. The messages table maps each flag to a clear sentence.
  • One input listener on the form handles all fields through event bubbling, checking whichever field changed.
  • classList.toggle("bad", condition) switches the red or green border, and aria-invalid plus aria-describedby let screen readers announce the error (see Accessibility Basics).
  • On submit, preventDefault() stops the page from reloading. All fields are checked; if any fail, focus jumps to the first bad one, otherwise a success message appears.

Try it: submit the empty form, then type a name and a mobile number such as 01712345678.

Password Strength Checker

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Password checker</title>
  <style>
    body { font-family: sans-serif; margin: 10px; }
    input { font-size: 15px; padding: 6px; width: 240px; }
    ul { list-style: none; padding: 0; margin: 8px 0; }
    li::before { content: "\2716  "; color: #c62828; }
    li.met::before { content: "\2714  "; color: #2e7d32; }
    .bar { height: 8px; width: 250px; background: #eceff1; border-radius: 4px; }
    .fill { height: 100%; width: 0; border-radius: 4px; transition: width .2s, background .2s; }
  </style>
</head>
<body>
  <label for="pw">Choose a password</label><br>
  <input id="pw" type="password" autocomplete="new-password">
  <div class="bar"><div class="fill" id="fill"></div></div>
  <ul id="rules"></ul>
  <script>
    const rules = [
      ["At least 8 characters", s => s.length >= 8],
      ["A lowercase letter", s => /[a-z]/.test(s)],
      ["An uppercase letter", s => /[A-Z]/.test(s)],
      ["A number", s => /\d/.test(s)],
      ["A symbol such as ! or #", s => /[^A-Za-z0-9]/.test(s)],
    ];
    const list = document.getElementById("rules");
    const items = rules.map(([text]) => {
      const li = document.createElement("li");
      li.textContent = text;
      list.append(li);
      return li;
    });
    const colours = ["#c62828", "#c62828", "#ef6c00", "#f9a825", "#7cb342", "#2e7d32"];

    document.getElementById("pw").addEventListener("input", e => {
      const value = e.target.value;
      let score = 0;
      rules.forEach(([, test], i) => {
        const ok = test(value);
        items[i].classList.toggle("met", ok);
        if (ok) score++;
      });
      const fill = document.getElementById("fill");
      fill.style.width = (score / rules.length) * 100 + "%";
      fill.style.background = colours[score];
    });
  </script>
</body>
</html>

Result

  • Each rule is a pair: a description and a test function. Adding a rule means adding one line.
  • The checklist items are created once with createElement, then updated on every keystroke by toggling the met class, which swaps the cross for a tick through CSS ::before.
  • The score (0 to 5) sets the width and colour of the strength bar. A CSS transition makes the change smooth.
  • autocomplete="new-password" lets password managers offer a strong generated password.

The validity Object

PropertyTrue whenSet by
valueMissingField is emptyrequired
typeMismatchNot a valid email or URLtype="email", type="url"
patternMismatchDoes not match the regexpattern
tooShort / tooLongLength outside limitsminlength, maxlength
rangeUnderflow / rangeOverflowNumber too small or bigmin, max
customErrorYou called setCustomValidity("message")JavaScript
validEverything passesAll of the above

form.checkValidity() returns true only if every field is valid, and input.setCustomValidity("") clears a custom error.

Common Mistakes

  1. Trusting browser validation alone. Anyone can bypass it, so the server must validate again.
  2. Showing errors before the user has typed anything, which feels hostile. Validate on input or on leaving a field.
  3. Error messages shown only by colour, invisible to colour-blind users.
  4. Clearing the whole form after one mistake, forcing users to retype everything.

Practice Exercises

Exercise 1. Add a “Confirm password” field that shows “Passwords do not match” when it differs from the first.

Show answer
const pw = document.getElementById("pw");
const confirm = document.getElementById("confirm");
confirm.addEventListener("input", () => {
  confirm.setCustomValidity(confirm.value === pw.value ? "" : "Passwords do not match");
  document.getElementById("confirm-msg").textContent = confirm.validationMessage;
});

Exercise 2. Disable the submit button until the whole form is valid.

Show answer
const btn = form.querySelector("button[type=submit]");
form.addEventListener("input", () => { btn.disabled = !form.checkValidity(); });
btn.disabled = true;

Frequently Asked Questions

Should I validate on input, on blur or on submit?

A common pattern is to validate a field when the user leaves it (blur) the first time, then live on every input once an error has been shown, and always on submit.

Do I still need server-side validation?

Yes, always. Client-side checks are for convenience; only the server can be trusted to protect your data.

Summary

  • Put basic rules in HTML attributes; read results from input.validity.
  • Show clear text messages next to fields and link them with ARIA.
  • Use preventDefault on submit and focus the first error.
  • Always validate again on the server.

Next: Drawing With the HTML Canvas.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *