Sub topic 7
Styling valid and invalid fields
This chapter shows how to style form fields by validation state with CSS alone. It assumes you know basic CSS selectors, the built-in constraint attributes (required, minlength, pattern, and so on), and how a control's validity property works from the previous chapters.
The validation pseudo-classes
The browser keeps a validation state for every form control, and CSS can select on it. You don't need JavaScript to apply a red border to a bad field.
| Selector | Matches |
|---|---|
| `:valid` | A control that satisfies all of its constraints |
| `:invalid` | A control that violates at least one constraint, including a custom error set with `setCustomValidity` |
| `:user-valid` | A valid control after the user has interacted with it |
| `:user-invalid` | An invalid control after the user has interacted with it |
| `:required` / `:optional` | Controls with or without the `required` attribute |
| `:in-range` / `:out-of-range` | Controls with `min` or `max` whose value is inside or outside the range |
| `:placeholder-shown` | A control that is currently displaying its placeholder text (the field is empty) |
:valid and :invalid also apply to <form> and <fieldset> elements. A form matches :invalid while any of its controls is invalid, which lets you style a section or a submit button based on the whole group.
Controls that are barred from constraint validation match neither :valid nor :invalid. These include disabled controls, readonly inputs, type="hidden" inputs, and buttons. If your styles seem to skip a field, check whether it is one of these.
Why `:invalid` alone is a trap
A required field is invalid the moment the page loads, because it is empty. If you write this rule, every required field is red before the user has typed anything.
/* Problem: fires on page load */
input:invalid {
border: 2px solid #c00;
}This is the most common mistake in form styling. You have three ways to avoid it.
- Use
:user-invalidand:user-valid. These match only after the user has interacted with the field. - Use
:invalid:not(:placeholder-shown). This hides the error while the field is empty. It needs aplaceholderattribute on each input, even a single space, and it never flags an empty required field after a failed submit. - Toggle a class from JavaScript, for example on
blurand on submit, and style the class.
The first option is the best one in current browsers.
How `:user-invalid` decides when to apply
The user-interaction pseudo-classes depend on a hidden flag the browser tracks for each control. The flag is set when the user changes the value and then leaves the field, or when the user tries to submit the form. After that, :user-invalid and :user-valid track the live validity of the field.
In the Untouched state, a field still matches the plain :valid or :invalid pseudo-class. Only the user- variants wait for interaction.
Two details matter in practice.
- A form that is submitted with
novalidate, or one where your script callspreventDefault(), still counts as a submit attempt in current browsers. The interaction flag is set, but check your target browsers because behavior at the edges has varied. - Resetting the form with
form.reset()clears the flag. Fields return to the untouched state.
A complete example
This page combines the pseudo-classes. Save it as an HTML file and open it in a current browser.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Styled validation</title>
<style>
label { display: block; margin-top: 1rem; font-weight: 600; }
input {
font: inherit;
padding: 0.4rem;
border: 2px solid #767676;
border-radius: 4px;
}
/* Mark required fields before any interaction */
input:required {
border-left-width: 6px;
}
/* Show state only after interaction */
input:user-invalid {
border-color: #b00020;
background: #fff5f5;
}
input:user-valid {
border-color: #1b6e2d;
}
/* Keep the focus indicator visible on top of state styles */
input:focus-visible {
outline: 3px solid #1a56db;
outline-offset: 2px;
}
/* Range feedback for fields with min or max */
input:out-of-range {
background: #fff8e1;
}
/* Style the whole form based on its state */
form:invalid button[type="submit"] {
opacity: 0.6;
}
</style>
</head>
<body>
<form id="signup" action="/signup" method="post">
<label for="username">Username (3 to 20 characters)</label>
<input id="username" name="username" required minlength="3" maxlength="20"
pattern="[a-z0-9_]+" title="Lowercase letters, digits, and underscores only">
<label for="age">Age</label>
<input id="age" name="age" type="number" min="18" max="120" step="1">
<button type="submit">Sign up</button>
</form>
</body>
</html>Walk through what happens. On load, the username field has a thicker left border (from :required) but no error color. Type ab and press Tab. The field has fewer than 3 characters, so it now matches :user-invalid and turns red. Fix it to abc and the border turns green immediately.
The age field is optional, so an empty age is valid. Type 15 and :out-of-range applies the amber background. The value is also invalid, so after you leave the field :user-invalid applies as well. When two rules set the same property, the one later in the stylesheet with equal specificity wins. Put the more important state last.
Do not rely on color alone
A red border is invisible to some users with color vision deficiency, and it says nothing to a screen reader. WCAG 1.4.1 requires that color is not the only way to convey information. Add at least one non-color signal.
- Show a text message next to the field. The accessible-errors chapter covers how to link it to the control.
- Add an icon with a background image or a pseudo-element on a wrapper.
- Change the border style or width, not just its hue.
Keep contrast in mind too. The border of a form control needs a contrast ratio of at least 3:1 against its background (WCAG 1.4.11). Pale reds and light greens often fail.
.field:has(input:user-invalid)::after {
content: "Check this field";
display: block;
color: #8a0019;
font-size: 0.875rem;
}This rule uses :has() to react to the child input's state. It works for a quick visual hint, but generated content is not reliably announced by screen readers. Use a real element for the message.
Hooking into JavaScript state
CSS pseudo-classes read the browser's built-in validation state. If you manage errors in JavaScript, as in the earlier submit handler, you can style from the attributes your script writes.
input[aria-invalid="true"] {
border-color: #b00020;
background: #fff5f5;
}This approach gives you two benefits. The styling and the accessibility state come from the same source, so they cannot disagree. It also works with novalidate, because the selector depends on an attribute you control and not on the browser's flag timing.
Custom errors work with the pseudo-classes without extra code. When setCustomValidity('Passwords do not match.') is active, the control matches :invalid, and after interaction it matches :user-invalid. Clearing it with an empty string removes the match.
Browser support and fallbacks
:user-invalid and :user-valid are supported in current Chrome, Edge, Firefox, and Safari (Safari from 16.5). Older browsers drop a rule they cannot parse. This is a risk when you put several selectors in one rule, because one unknown selector invalidates the whole list.
/* Wrong: older browsers ignore the whole rule */
input:user-invalid,
input:invalid:not(:placeholder-shown) {
border-color: #b00020;
}
/* Right: separate rules, fallback first */
input:invalid:not(:placeholder-shown) {
border-color: #b00020;
}
@supports selector(:user-invalid) {
input:invalid:not(:placeholder-shown):not(:user-invalid) {
border-color: inherit;
}
input:user-invalid {
border-color: #b00020;
}
}The @supports selector() query lets you build a fallback layer. The second block removes the fallback styling where the better selector exists, so the two do not fight. If your audience uses only current browsers, skip the fallback and use :user-invalid directly.
Common errors
- Errors on page load. You used
:invalidon a required field. Switch to:user-invalid. - No styling on a field you expected to match. The control may be disabled,
readonly, or hidden, which excludes it from validation. - Styles that vanish after JavaScript replaces an input. A new element starts untouched, so it loses the interaction flag.
- Focus outline removed. Removing
outlineto show a custom border hides keyboard focus. Keep:focus-visiblestyles. - Green means correct.
:user-validmeans the value satisfies the browser's constraints, not that the server will accept it. Do not tell users a username is available because it matched a pattern. The server-side chapter explains why.
Summary
Use :user-invalid and :user-valid to show state after interaction, use :required and :out-of-range for static hints, and add a non-color cue and a text message. When you need to match your script's own state, select on aria-invalid.
Exercise
A signup form has input:invalid { border-color: red; }. Testers report that the form looks full of errors when it first opens. Explain the cause and give the one-line change that fixes it for current browsers. Then name one reason a red border alone is still not enough.
Show answer
Required fields (and other fields with unmet constraints) match :invalid immediately, because validity is computed from the initial empty value, not from user actions. Change the selector to input:user-invalid, which matches only after the user has edited and left the field or tried to submit. A red border alone is not enough because color cannot be the only indicator (WCAG 1.4.1): users with color vision deficiency may not see it, and screen readers do not announce it. Add a text message linked to the field and a non-color cue.
Exercise
You write input:user-invalid, input:invalid:not(:placeholder-shown) { border-color: red; } and an old browser shows no red border for any invalid field. Why, and how do you restructure the CSS?
Show answer
A browser that does not recognize :user-invalid treats the whole selector list as invalid and drops the entire rule, including the part it could have understood. Split the selectors into separate rules: put the :invalid:not(:placeholder-shown) rule first as the fallback, and put :user-invalid in its own rule (optionally inside @supports selector(:user-invalid)).