User-Invalid and User-Valid: The Pseudo-Classes That Save the Day

User-Invalid and User-Valid: The Pseudo-Classes That Save the Day

Lets learn how :user-invalid and :user-valid can make form validation easier

Forms can be a pain to validate, especially the individual elements. CSS has pseudo-classes like :invalid and :valid, but they fire right away, without waiting for the user to finish interacting with the element. That's where the :user-invalid and :user-valid pseudo-classes come in. They only fire after the user has completed their interaction with the element.

:user-invalid

The :user-invalid pseudo-class matches any element with an invalid value, based on its validation constraints. It's different from the :invalid pseudo-class because it only applies to elements that the user has interacted with and that have an invalid value.

let's suppose we have an email element

<input type="email">

and we want to turn its background red only when the user has completed its interaction and it has an invalid value so then our CSS will look like this

input[type="email"]:user-invalid{
  background-color:red
}

:user-valid

The :user-valid pseudo-class matches an element with a valid value, based on its validation rules, after the user has completed their interaction. It's different from the :valid pseudo-class because it only applies to elements that the user has interacted with and that have a valid value.

Suppose we have an input element but we only want the number to be entered in it.

<input type="text" pattern="\d+"/>

now if we want to turn it green after the user has completed its interaction with it then our CSS will look like this

input[type="text"]:user-valid{
  background-color:green;
}

These pseudo-classes have decent support to use right now in your production code

You can play with it using the following playground

Thanks for reading