Reading history

HTML Form Validation

7 min read 0 views

Learn HTML form validation: required, pattern, min and max, :valid and :invalid styles, and custom messages with setCustomValidity.

A form that accepts “rafi.mail.com” as an email address, or 15 when the minimum age is 16, creates problems later. HTML can check most of these rules by itself, before anything is sent, using attributes such as required, pattern and min. CSS can then show the user which fields need fixing. For rules HTML cannot express, such as “the two passwords must match”, a few lines of JavaScript plug into the same system.

In this lesson you will learn

  • Validation attributes: required, minlength, pattern, min, max
  • How input types like email and number check values
  • Styling fields with :valid, :invalid and :user-invalid
  • Custom rules and messages with setCustomValidity
  • Why server-side checks are still essential

You should know HTML forms and styling forms.

Built-In Validation

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Built-in form validation</title>
  <style>
    body { font-family: sans-serif; margin: 12px; font-size: 14px; }
    form { display: grid; gap: 8px; max-width: 340px; }
    label { display: grid; gap: 3px; }
    input { padding: 6px 8px; border: 2px solid #ccc; border-radius: 6px; font: inherit; }
    /* Red when a filled-in field breaks a rule; empty fields stay neutral */
    input:invalid:not(:placeholder-shown) { border-color: #e53935; background: #ffebee; }
    input:valid:not(:placeholder-shown) { border-color: #43a047; }
    small { color: #666; }
  </style>
</head>
<body>
  <form>
    <label>Full name
      <input name="name" required minlength="3" placeholder="At least 3 letters">
    </label>
    <label>Email
      <input type="email" name="email" required placeholder="you@example.com" value="rafi.mail.com">
    </label>
    <label>Mobile (Bangladesh)
      <input type="tel" name="phone" required pattern="01[3-9][0-9]{8}" placeholder="01XXXXXXXXX" value="01712345678">
      <small>11 digits starting with 013 to 019</small>
    </label>
    <label>Age
      <input type="number" name="age" min="16" max="60" value="15" placeholder="16 to 60">
    </label>
    <button>Register</button>
  </form>
</body>
</html>

Result

  • required means the field cannot be empty. minlength="3" sets the shortest allowed text.
  • type="email" checks for an @ and a sensible shape, so “rafi.mail.com” fails.
  • pattern is a regular expression the whole value must match. 01[3-9][0-9]{8} means “01”, then a digit from 3 to 9, then exactly 8 more digits: the shape of a Bangladeshi mobile number.
  • type="number" with min="16" and max="60" rejects 15.
  • The CSS turns a filled-in field red when :invalid matches, and green when :valid matches. :not(:placeholder-shown) keeps empty fields neutral, so the form does not shout at users before they start.
  • Press Register: the browser stops the submission and shows a message beside the first problem field.
Attribute or typeChecks
requiredNot empty
minlength / maxlengthText length
min / max / stepNumber and date ranges
patternMatches a regular expression
type="email", type="url"Email or web address format

:user-invalid

Newer browsers support :user-invalid. It matches only after the user has changed the field or tried to submit, which is often exactly when you want to show an error. It is a good alternative to the :placeholder-shown trick.

Custom Rules and Messages

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Custom messages with the Constraint Validation API</title>
  <style>
    body { font-family: sans-serif; margin: 12px; font-size: 14px; }
    form { display: grid; gap: 8px; max-width: 320px; }
    input { padding: 6px 8px; border: 2px solid #ccc; border-radius: 6px; font: inherit; }
    .error { color: #c62828; font-size: 13px; min-height: 1.2em; }
  </style>
</head>
<body>
  <form id="f" novalidate>
    <label>Password <input id="pw" type="password" required minlength="8" value="abc"></label>
    <label>Confirm <input id="pw2" type="password" required value="abd"></label>
    <div class="error" id="msg" aria-live="polite"></div>
    <button>Create account</button>
  </form>
  <script>
    const form = document.getElementById("f");
    const pw = document.getElementById("pw"), pw2 = document.getElementById("pw2");
    const msg = document.getElementById("msg");

    function check() {
      // minlength only checks text the user typed, so check the length ourselves too
      pw.setCustomValidity(pw.value.length < 8
        ? `Password needs 8+ characters (you typed ${pw.value.length}).` : "");
      // A rule the browser cannot know: the two passwords must match
      pw2.setCustomValidity(pw.value === pw2.value ? "" : "Passwords do not match.");
      msg.textContent = pw.validationMessage || pw2.validationMessage;
      return form.checkValidity();
    }
    form.addEventListener("submit", e => { if (!check()) e.preventDefault(); });
    pw.addEventListener("input", check);
    pw2.addEventListener("input", check);
    check();   // run once so the demo shows the messages straight away
  </script>
</body>
</html>

Result

  • novalidate on the form turns off the browser’s own pop-up messages, so the page can show its own message in the red text area.
  • setCustomValidity("message") marks a field as invalid with your own message. An empty string marks it valid again. This is how the “Passwords do not match” rule works.
  • minlength only checks text the user actually typed, not a value written in the HTML. The code checks the length itself so the demo shows the message straight away.
  • form.checkValidity() returns true only when every field passes. The submit handler calls preventDefault() to stop sending an invalid form.
  • aria-live="polite" makes screen readers announce the error message when it changes.
  • Try it: type a longer password in both boxes, and the message disappears.

Always Check on the Server Too

Browser validation is there to help honest users fix mistakes quickly. It is not security. Anyone can turn off JavaScript, edit the HTML in developer tools, or send data straight to your server without using the form. Every rule must be checked again on the server before data is saved.

Common Mistakes

  1. Trusting browser validation alone, with no server-side checks.
  2. Showing errors before the user has typed anything, which makes a fresh form look broken.
  3. Error messages that do not say how to fix the problem, such as “Invalid input”. Say what is expected, as the mobile number hint does.
  4. Using colour alone to show errors. Add text too, for users who cannot see the difference between red and green.

Practice Exercises

Exercise 1. Write an input for a 4-digit PIN that must be exactly 4 digits.

Show answer
<input name="pin" inputmode="numeric" required pattern="[0-9]{4}"
       title="Exactly 4 digits">

inputmode="numeric" shows a number keypad on phones, and title is included in the browser’s error message.

Exercise 2. Add a date field for a booking that cannot be before 1 December 2026.

Show answer
<label>Booking date
  <input type="date" name="date" required min="2026-12-01">
</label>

Date values use the YYYY-MM-DD format in HTML, whatever format the user sees.

Frequently Asked Questions

Can I change the browser’s error message text?

Partly. The title attribute adds a hint to pattern errors, and setCustomValidity replaces the message completely. For full control over the look, use novalidate and show your own messages, as in the second example.

Does pattern work on every input type?

It works on text-like inputs: text, tel, email, url, password and search. For numbers and dates, use min, max and step instead.

Summary

  • HTML attributes and input types check most simple rules without any JavaScript.
  • :valid, :invalid and :user-invalid let CSS show which fields need attention.
  • setCustomValidity and checkValidity add your own rules and messages.
  • Browser checks help users; server checks protect your data.

Next: CSS Grid Template Areas and auto-fit.

Lessons are also marked complete when you click Next.

Leave a Reply

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