Skip to content Paweł Grzybek

CSS valid/invalid vs user-valid/user-invalid pseudo-classes

CSS offers many input value-checking pseudo-classes. The :valid and :invalid are very common, and we use them to apply styling based on the input validity. The fact that they are applied immediately, without any user interaction, can be confusing. Why would you like to see an error about the incorrect email address before you even could fill it out?

Back in 2014, there was a proposal to add :changed/:edited/:altered/:dirty to solve this problem, but I don’t think it went anywhere. This is why many popular component frameworks delegate this functionality to JavaScript. Luckily there is a way to achieve this with CSS only, using :user-valid/:user-invalid pseudo-classes. Unfortunately, browser support is limited to Safari and Firefox when writing this post. Have a look at the example:

.user-invalid-message,
.invalid-message {
  display: none;
  color: red;
}

input:user-invalid ~ .user-invalid-message,
input:invalid ~ .invalid-message {
  display: block;
}

See the Pen Untitled by Pawel Grzybek (@pawelgrzybek) on CodePen.

I just learned about this today from the series of posts about progressively enhanced form validation by Gerardo Rodriguez. I highly recommend the whole series. I hope other browsers follow Firefox and Safari and implement this feature soon.

Hopefully, this helps! Peace ✌️

Leave a comment

👆 you can use Markdown here

Your comment is awaiting moderation. Thanks!