Style form errors after interaction
Use :user-invalid to style a required field after the user leaves it with a changed value or attempts to submit the form.
You open your signup page and every required field already has a red border. Nobody has typed anything. The CSS uses :invalid, and an empty required field is invalid from the moment the page loads.
The error before the first keystroke
Open this HTML file to reproduce the early error styling.
<style>
input:invalid { border-color: crimson; }
</style>
<form>
<label>Email <input type="email" required /></label>
<label>Name <input required /></label>
<button>Sign up</button>
<button type="reset">Reset</button>
</form>Both inputs render red on load. :invalid reports the field's state, and an empty required field fails its constraint before anyone touches it.
Swap in :user-invalid
Replace the CSS inside <style> with the two rules below. Both selectors wait for the browser to mark the field as interacted with.
input:user-invalid { border-color: crimson; }
input:user-valid { border-color: seagreen; }The form now loads with neutral borders. Try these steps in Chromium to see each selector take effect.
diagram
When each validity selector matches
Type sam@ into Email, then click Name. Email turns red when you leave it. Return to Email and type example.com to turn it green while it still has focus.
The same selector can reveal a message. To show a hint, give the input an id and link the label to it with for. Place a .hint paragraph after the input as its sibling. Hide it with .hint { display: none; } and reveal it with input:user-invalid + .hint { display: block; }.
When the browser flags a field
Both selectors require the control to take part in constraint validation and have its user validity flag set. In the Chromium example, editing the email and moving focus away sets that flag. Afterward, the selectors follow the field's validity as you type. See the HTML matching rules.
Tab through a fresh, empty field and its border stays neutral. Press Sign up with both fields empty and both borders turn red. Reset clears the flag and restores the neutral borders.
Older browsers
Firefox added both selectors in version 88, Safari in 16.5 and Chrome in 119. See browser compatibility. A browser that does not know a selector drops the whole rule, and that includes every other selector in the same list. Give :user-invalid a rule of its own instead of writing input:user-invalid, input.error, or the .error fallback disappears with it.