Skip to content
Tutorials Center
My learning

Topics

Lesson 71 of 122 ยท Forms

Form Validation

Let the browser check input with required, type, min, max, pattern and length, style errors with :user-invalid, and add custom rules with the validation API.

People make typing mistakes. They skip a field, put a space in their email address, or choose a check-out date before the check-in date. Client-side validation catches those mistakes in the browser, before the form is sent, so people can fix them right away instead of waiting for the server to complain.

HTML has a complete validation system built in. You describe the rules with attributes, and the browser checks them, blocks the submission and points at the problem, all without JavaScript. When you need more, a small JavaScript API lets you add custom rules and messages. This lesson covers both, and ends with the most important rule of all: the server must check everything again.

Rules you already know

Many attributes from earlier lessons are validation rules. Here they are in one place:

Rule Fails when Works on
required The field is empty (or no radio in the group is chosen) Most inputs, <select>, <textarea>
type="email" / type="url" The value is not a valid email address or absolute URL Those input types
min / max The value is too low or too high Numbers, ranges, dates and times
step The value is between allowed steps Numbers, ranges, dates and times
minlength / maxlength The text is too short or too long Text-like inputs, <textarea>
pattern The value does not match the regular expression Text-like inputs

Two details are easy to miss. First, every rule except required ignores empty fields: an empty optional email field is perfectly valid. Second, minlength is only checked after the person has edited the field, so a value set by your code will not trigger it.

When the browser checks

The browser validates when the form is submitted. If any control is invalid, it cancels the submission, focuses the first invalid control and shows a message bubble next to it. The submit event does not fire at all, which is why the handler in our examples only ever sees valid data.

Built-in validation

Press Create account with everything empty, then fix one problem at a time: an email without @, age 12, username Ana!. Each time, the browser explains what is wrong. The wording and look of the bubble come from the browser and match the person's language settings.

Styling valid and invalid fields

Every control has a validity state you can style with CSS pseudo-classes:

  • :valid and :invalid match controls that currently pass or fail their rules.
  • :required and :optional match controls with and without required.
  • :in-range and :out-of-range match number and date controls against min and max.

There is a catch with :invalid: an empty required field is invalid from the moment the page loads. Style :invalid with a red border, and people see a page full of errors before they have typed a single letter.

The fix is :user-invalid (and its partner :user-valid). These match only after the person has interacted with the field, typically after they change it and move on, or after they try to submit. That is exactly when an error message is helpful:

HTML
<style>
  input:user-invalid {
    border-color: #c0362c;
    outline-color: #c0362c;
  }
  input:user-valid {
    border-color: #2f855a;
  }
</style>

:user-invalid works in all current major browsers. In older browsers the styles simply do not apply, and the built-in bubbles still work.

Never rely on color alone. Some people cannot tell red from green. Pair a colored border with a text message, or an icon that has a text alternative.

The constraint validation API

For anything the attributes cannot express, JavaScript gives every control a small validation API:

  • control.validity is an object of true/false flags that say why a field is invalid: valueMissing, typeMismatch, patternMismatch, tooShort, tooLong, rangeUnderflow, rangeOverflow, stepMismatch, badInput, customError, and finally valid.
  • control.validationMessage is the message the browser would show.
  • control.checkValidity() returns true or false, and fires an invalid event on failure.
  • control.reportValidity() does the same and also shows the message bubble.
  • control.setCustomValidity(message) marks the field as invalid with your own message. Passing an empty string "" marks it valid again.

The form element has checkValidity() and reportValidity() too, which check every control inside it.

Custom rules with setCustomValidity

A classic example is a "confirm password" field. No attribute can say "must equal the other field", but a few lines of script can:

Custom rules with setCustomValidity

Type two different passwords: the second field turns red, the message appears, and submitting shows the browser's bubble with your message. The repeat field has no name, so it is never sent; the server only needs one copy.

Always clear a custom error. A field stays invalid for as long as its custom message is a non-empty string. Forget to call setCustomValidity("") when the problem is fixed, and the form can never be submitted.

Your own messages with novalidate

If you want to show all errors as text on the page instead of bubbles, add novalidate to the form (Form Attributes explains it) and check validity yourself on submit:

HTML
<script>
  form.addEventListener("submit", (event) => {
    if (!form.checkValidity()) {
      event.preventDefault();
      for (const control of form.elements) {
        const box = document.getElementById(`${control.id}-error`);
        if (box) box.textContent = control.validationMessage;
      }
      form.querySelector(":invalid")?.focus();
    }
  });
</script>

Keep the HTML rules on the controls: the script reads them through checkValidity() and validationMessage, so you write each rule only once.

Writing helpful error messages

Whether the browser or your script shows them, good messages share a few traits:

  • Say what to do, not just what went wrong. "Enter a date after your check-in date" beats "Invalid date."
  • Show the rule before people break it. Put format hints next to the field, connected with aria-describedby, as the username hint above does.
  • Do not blame. "Enter your email address" is friendlier than "You forgot your email."
  • Validate on submit or when people leave a field, not on every keystroke from the first letter. Nobody enjoys an error for an email address they have not finished typing.

Why the server must validate too

Client-side validation is a convenience for honest people. It is not security. Anyone can:

  • Remove required or pattern with DevTools in seconds.
  • Disable JavaScript, which removes your custom rules.
  • Skip the form entirely and send a request straight to your server with a script.

So the server must check every value again, every time: types, lengths, ranges, allowed options, file types and permissions. Think of the two layers like this: the browser gives quick, friendly feedback; the server makes the final decision. A form that only validates in the browser is a form that accepts anything. You will put both layers together in Project: Accessible Contact Form.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. An optional email field (no required) is left empty. Is the form valid?

    Type, pattern, length and range checks only run when there is a value. Add required to make a field mandatory.
  2. 2. Why is :user-invalid usually better than :invalid for error styles?

    :invalid matches empty required fields as soon as the page loads. :user-invalid waits until the person has had a chance to fill the field in.
  3. 3. You called setCustomValidity with a message when two passwords did not match. The person fixes the mismatch. What must your code do?

    A custom error stays until you replace it with an empty string. Otherwise the form can never be submitted.
  4. 4. Why must the server validate data that the browser already checked?

    Browser validation helps honest people fix mistakes quickly. Anyone can bypass it, so the server must make the final decision.

Summary

  • required, type, min/max, step, minlength/maxlength and pattern let the browser validate without JavaScript; only required applies to empty fields.
  • On submit, the browser blocks invalid forms, focuses the first problem and shows a message; the submit event fires only for valid forms.
  • Style errors with :user-invalid and :user-valid so untouched fields are not flagged, and never rely on color alone.
  • validity, checkValidity(), reportValidity() and setCustomValidity() add custom rules and messages; clear custom errors with "".
  • Client-side validation is a convenience. The server must always validate again.

Next up: Output, Meter and Progress, three elements for showing results and measurements.