7.4 · Forms & UI

Errors at the right time: :user-valid and :user-invalid

Show validation only after the user has actually interacted with a field.

:invalid matches from the moment the page loads, so an empty required field is red before anyone has typed. That’s why most sites added JavaScript to track “touched” fields.

:user-invalid and :user-valid match only after the user has changed the field and moved on, or tried to submit the form.

Before
input.addEventListener('blur', () => {
  input.classList.add('touched')
})

input.touched:invalid { … }
Now
input:user-invalid {
  border-color: crimson;
}

input:user-valid {
  border-color: green;
}