Built-in Form Validation

Beginner · 23 min

The validation attributes (required, pattern, min, max, minlength), which controls skip validation, and when :invalid and :user-invalid apply.

Before thisButtons and Submit Behavior

Steve Griffith - Prof3ssorSt3v3 · 23 min

Built-in Form Validation

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Steve Griffith - Prof3ssorSt3v3Report a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Attributes such as `required`, `minlength`, `maxlength`, `min`, `max`, `step` and `pattern`, plus the `type` of the input, make the browser check the form on submit and block it when a control is invalid. No JavaScript is involved.
  • `:invalid` matches from the moment the page loads: in a test, an empty required field was `:invalid` before anyone touched it. `:user-invalid` waits until the user has interacted, so it is the one to style for error feedback.
  • `pattern` is anchored to the whole value, and it is skipped when the field is empty. Pair it with `required` if empty is not allowed.
  • `minlength` only applies to text the user typed. In a test, a value set from the HTML or by a script with 3 characters against `minlength="5"` was valid, and typing 3 made it invalid.
  • The message wording differs between browsers and cannot be styled, and validation can be turned off with the user's console. It improves the experience, and the server must check everything again.

Why the browser validates for you

Before HTML5, every form that wanted to reject an empty name or a malformed email needed a script. Most scripts were written badly, and many were skipped, so bad data reached the server. Built-in validation moves the common checks into the browser: you state the rule in an attribute, and the browser enforces it when the user submits, with a message and focus on the first problem.

It will not replace server checks, because it can be bypassed by turning off scripts or sending the request by other means, and the rules it knows are limited. What it does is give a free first line of defense with no code. The frontend roadmap’s forms lesson places this in the wider picture; here are the mechanics.

The constraint attributes

<input name="age" type="number" min="18" max="120" required>
<input name="code" pattern="[A-Z]{3}[0-9]{3}" required>
<textarea name="bio" minlength="20" maxlength="300"></textarea>
  • required: must have a value. For a checkbox, it must be checked, and for a radio group, one must be picked.
  • min, max, step: bounds and granularity for numbers, ranges and dates. With min="1" and step="2", the allowed numbers are 1, 3, 5. In a test, 4 produced a step mismatch and 5 did not.
  • minlength, maxlength: text length.
  • pattern: a regular expression the whole value must match.
  • type: email and url check their format, and the number and date types check that the text parses.

I read the validation state of a form with each of these in headless Chromium, Firefox and WebKit. A required empty field, an unchecked required checkbox, an unselected required radio, a required <select> with an empty first option, a pattern mismatch, a bad email and a bad URL were each :invalid.

pattern details

The pattern is implicitly anchored, as if wrapped in ^(?: and )$. In a test, [a-z]+ accepted abc and rejected xabc1, so it is a whole-value check, not a search. It is skipped for an empty value: a field with pattern and no required was valid when empty. Use title to describe the format, since browsers may show it in the message. The pattern uses JavaScript regular expression syntax, covered in the regular expressions lesson.

The “dirty” rule for length

minlength and maxlength are the odd ones. They check only text the user has typed. In a test, an input with value="ab" in the HTML and minlength="5" was valid on load. Setting the value from a script left it valid. After the user typed three characters, validity.tooShort became true. The reason is that a default value is the author’s choice, so flagging it would only confuse the user. It matters when you prefill a form from stored data and expect the minimum to be enforced.

Which controls are skipped

Not every control is validated. A control with disabled, readonly or type="hidden" is exempt, as is a button that is not a submit button. In a test, all of those had willValidate of false, including a required readonly input. The same goes for the whole form if it has novalidate, or if the submit button has formnovalidate. That is useful for “Save draft”, and it is also how a required readonly field slips through, so do not rely on required for fields the user cannot change.

When feedback appears

The browser checks when the user tries to submit. It does not nag while they type. If a field fails, the submit event does not fire, the browser shows a message bubble next to the first invalid control and focuses it. In a test, a submit click with an empty required field produced no submit event.

CSS has two pseudo-classes for the state. :invalid matches whenever the control fails a rule, including before the user has done anything. In a test, an empty required field matched :invalid on load. That makes input:invalid { border-color: red } a bad idea: the whole form is red on arrival. :user-invalid matches only after the user has interacted. In the test, it did not match while the field was focused after typing and deleting a character, and it matched after the field lost focus. Browser support is good: according to web-features 3.47.0, :user-invalid and :user-valid shipped in Chrome 119, Firefox 88 and Safari 16.5, and are Baseline widely available. Style the :user-invalid state for feedback and leave :invalid for logic. Pseudo-classes and pseudo-elements covers the CSS side.

What you do not control

The message text is the browser’s. For an empty required field, Chromium and Firefox said “Please fill out this field.” and WebKit said “Fill out this field”. For a bad email, Chromium named the missing @ and Firefox said “Please enter an email address.” You cannot style the bubble, and it varies by language and browser. If you need exact wording or styling, the constraint validation API lets you take over. I could not see the bubble in headless browsers, only read the messages from validationMessage.

Remember the limits: built-in checks cannot compare two fields, check a username against a database or handle conditional rules, and they run only in the browser. See input validation and injection attacks for the server side.

What the video covers

The embed is the whole of Steve Griffith’s “Form Validation I - HTML and CSS” (February 2021), the first of two parts. Its description says it explains the attributes you can add to form elements and the CSS pseudo-classes related to the use of, interaction with and validation of forms. There are no chapters, and I could not read a transcript. It is from 2021, so it predates :user-invalid becoming available across browsers, and the lesson above covers that. The part two video, on the JavaScript side, is the runner-up for the next lesson. Kevin Powell’s shorter video on CSS-only hints is also linked.

Where this fits

This follows buttons and submit behavior. The next lesson, the constraint validation API, covers taking control of the messages. Validation errors also need to be announced, which is covered in accessible names and descriptions.

Check yourself

  1. 01You style `input:invalid { border: 2px solid red }`. Users complain the empty required fields are red as soon as the page loads. What is the fix?

    `:invalid` applies as soon as the control fails its constraints, including on load. Use `:user-invalid`, which matches only after the user has interacted with the field. In a test, an empty required field was `:invalid` immediately and became `:user-invalid` only after the user typed and left it.

  2. 02`<input pattern="[a-z]+">` holds `abc123`. Is it valid, and what about an empty field?

    `abc123` is invalid: the pattern is anchored to the whole value, so digits break it. An empty field is valid, because `pattern` is only checked when there is a value. Add `required` to reject an empty value.

  3. 03A text field in the HTML is `value="ab" minlength="5"`. Is it valid?

    Yes, until the user edits it. `minlength` and `maxlength` check only user input, so an initial or script-set value is exempt. In a test, typing three characters then made the field `tooShort`.

  4. 04Which controls skip validation entirely?

    Disabled controls, readonly controls, `type="hidden"` and buttons that are not submit buttons. In a test their `willValidate` was `false`, even for a `required` field. A form with `novalidate` is different: its controls still have constraints, but submitting it skips the check.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark