Sub topic 12
Styling Valid and Invalid States
This chapter assumes you can build a form with labeled controls and that you know the built-in validation attributes (required, pattern, min, max, minlength). It also assumes basic CSS selectors. You will learn which pseudo-classes the browser exposes for validation state, why the obvious approach shows errors too early, and how to style errors in a way that is accessible.
The validation pseudo-classes
The browser tracks the validity of every control that takes part in constraint validation. CSS can read that state through pseudo-classes, so you do not need JavaScript to toggle classes.
| Pseudo-class | Matches |
|---|---|
| `:valid` | A control that satisfies all of its constraints. Also matches controls with no constraints. |
| `:invalid` | A control that fails at least one constraint. |
| `:required` | A control with the `required` attribute. |
| `:optional` | A control without `required`. |
| `:in-range` | A `number`, `range`, or date control whose value is within `min` and `max`. |
| `:out-of-range` | The same control types with a value outside `min` and `max`. |
| `:user-valid` | A valid control, but only after the user has interacted with it. |
| `:user-invalid` | An invalid control, but only after the user has interacted with it. |
| `:placeholder-shown` | A control currently displaying its placeholder, which means it is empty. |
:valid and :invalid also apply to the form and fieldset elements. A form matches :invalid if any of its controls is invalid. That lets you style a whole group, for example by dimming the submit button.
The problem with plain :invalid
Validity is evaluated from the moment the page loads. A required empty field is invalid before the user has typed anything. This style therefore paints every required field red on page load:
input:invalid {
border-color: #b00020;
}Users see a screen full of errors for a form they have not started. This is the most common mistake in validation styling.
In the diagram, PristineInvalid matches :invalid but not :user-invalid. UserInvalid matches both.
Using :user-invalid
:user-invalid and :user-valid solve the timing problem. A control matches :user-invalid only after the user has interacted with it in a meaningful way, such as editing the value and moving focus away, or after a submit attempt. The exact trigger is decided by the browser, but the intent is the same everywhere: do not shout before the user has had a chance.
<form action="/subscribe" method="post" novalidate>
<label for="email">Email address</label>
<input id="email" name="email" type="email" autocomplete="email" required>
<p class="hint" id="email-hint">We send one message a week.</p>
<button type="submit">Subscribe</button>
</form>
<style>
input {
border: 2px solid #767676;
padding: 0.4rem 0.6rem;
border-radius: 4px;
}
input:user-valid {
border-color: #1b7f3b;
}
input:user-invalid {
border-color: #b00020;
background: #fff5f5;
}
input:focus-visible {
outline: 3px solid #1a56db;
outline-offset: 2px;
}
</style>I added novalidate so that the browser does not block submission in this example. Remove it if you want the built-in bubbles. Note that novalidate turns off only the blocking and the bubbles. The pseudo-classes still work.
:user-invalid is supported in current versions of Chrome, Edge, Safari, and Firefox, but it is newer than :invalid. If you must support older browsers, use the fallback in the next section. Check a compatibility table before relying on it.
A fallback without :user-invalid
Before :user-invalid existed, developers used a placeholder trick. Give each control a placeholder of a single space. While the control is empty, :placeholder-shown matches. Once the user types, it stops matching.
input:not(:placeholder-shown):invalid {
border-color: #b00020;
}This styles a field as invalid only when it has content that fails validation. It has two weaknesses. An empty required field never gets an error style, even after the user tabs past it. And the single-space placeholder is a hack that other developers may remove.
A second option is to set a class from JavaScript on the blur event and write CSS against that class:
document.querySelectorAll('input, select, textarea').forEach((control) => {
control.addEventListener('blur', () => {
control.classList.add('touched');
});
});.touched:invalid {
border-color: #b00020;
}This works in all browsers and gives you full control over the timing, at the price of a script.
Styling ranges and optional fields
:in-range and :out-of-range apply only to controls that have a min or max. A number input with no bounds never matches either one.
input[type="number"]:out-of-range {
color: #b00020;
font-weight: 600;
}
input:required {
border-left: 4px solid #1a56db;
}Marking required fields with :required is useful, but it should not be the only cue. See the accessibility section below.
Styling the group
Because fieldset and form also match :invalid, you can react to the state of a whole section.
fieldset:invalid legend::after {
content: " (incomplete)";
color: #b00020;
}
form:invalid button[type="submit"] {
opacity: 0.6;
}Be careful with the second rule. Dimming a submit button is fine, but do not disable it for this reason. A disabled button gives users no way to learn what is wrong, and it is skipped by keyboard focus. Leave the button enabled and let the validation messages explain the problem.
A related gotcha concerns radio groups. If any radio button in a group has required, the whole group is invalid until one is chosen, and every radio in the group matches :invalid. Your CSS then marks each radio button, not the group. Style the fieldset instead.
Accessibility: color is not enough
A red border carries no meaning for a person who cannot see it or cannot tell red from green. Follow these rules.
- Never use color as the only signal. Add an icon, text, or a change in border style or weight.
- Keep a contrast ratio of at least 3:1 between a control's border and the background, and 4.5:1 for text.
- Do not remove the focus outline unless you replace it with a visible one.
- Pseudo-classes change only appearance. Screen readers do not announce
:invalidstyling. Pair the style with a text message tied to the control byaria-describedby, and setaria-invalid="true"when the value is wrong.
The last point connects to the chapter on accessible error messages. As a preview, the pattern looks like this:
<label for="zip">ZIP code</label>
<input id="zip" name="zip" inputmode="numeric" pattern="[0-9]{5}"
required aria-describedby="zip-error">
<p id="zip-error" class="error" hidden>Enter exactly five digits.</p>.error {
color: #b00020;
}
.error::before {
content: "\26A0\00a0";
}The warning symbol in ::before gives a second cue beyond color. Showing and hiding the message is a job for JavaScript, which later chapters cover.
Common mistakes
- Using
input:invalidalone, which flags untouched fields on load. - Assuming
:validmeans "correct." A field with no constraints is always:valid, and an empty optional field is:validtoo. - Treating
:validstyling as proof of server-side safety. The browser's check is a convenience. The server must validate again. - Removing
outlinefor:focuswithout a replacement. - Disabling the submit button to signal invalid state.
- Expecting
:user-invalidto match on page load. It will not, by design.
Putting it together
A practical pattern is: use :user-invalid and :user-valid for border and background changes, add a visible text message linked with aria-describedby, keep the focus outline strong, and use :placeholder-shown or a touched class only as a fallback for older browsers.
Exercise
A signup form has a required email field styled with input:invalid { border-color: red; }. Testers report that the field is red as soon as the page opens. Explain why, and give a one-line selector change that fixes it in modern browsers.
Show answer
An empty required field fails its constraint from page load, so it matches :invalid before the user does anything. Replace the selector with input:user-invalid, which matches only after the user has interacted with the field or tried to submit.
Exercise
Write a CSS rule that marks a number input with min="1" max="10" in bold dark red when its value is outside the allowed range. Why does the same rule do nothing for a number input without min or max?
Show answer
input[type="number"]:out-of-range { color: #b00020; font-weight: 600; }. :out-of-range needs at least one bound to compare against. Without min or max, no value can be out of range, so the input never matches.
Exercise
Your design uses only a red border for invalid fields. Name two changes that make the error accessible to users who cannot perceive the color or who use a screen reader.
Show answer
Add a visible text message (optionally with an icon) next to the field and link it with aria-describedby, and set aria-invalid="true" on the control while it is invalid. The text and icon work without color, and the ARIA attributes expose the error to screen readers.