Course contentsShow
← Web Development
Lesson 452 of 2,9828. Advanced CSS Selectors and FeaturesFree lesson

:user-valid and :user-invalid

Use these pseudo-classes to style validation states only after user interaction, avoiding premature error messages.

:user-valid and :user-invalid

You'll learn how to show validation feedback only after users interact with form fields, preventing annoying premature error messages.

The Problem with :valid and :invalid

You've already learned about :valid and :invalid pseudo-classes, but they have a significant drawback: they apply immediately when the page loads. This means an empty required field shows error styling before the user even touches it — frustrating and unhelpful!

Think of it like this: Imagine a teacher marking your test wrong before you've even picked up your pencil. Not very encouraging, right?

The Solution: Wait for User Interaction

:user-valid and :user-invalid solve this problem by only applying validation styles after the user has interacted with the field. These pseudo-classes wait until the user has edited the input or moved focus away from it before showing feedback.

How It Works

/* Only shows green border after user interacts and input is valid */
input:user-valid {
  border-color: green;
}

/* Only shows red border after user interacts and input is invalid */
input:user-invalid {
  border-color: red;
  background-color: #ffe6e6;
}

The browser tracks when a field becomes "user-interacted" — typically after the user types something or blurs the field. Before that moment, neither :user-valid nor :user-invalid will match, so your input stays neutrally styled.

Why This Matters

This approach creates a better user experience by:

  • Not overwhelming users with errors on page load
  • Providing feedback at the right moment (after they've tried)
  • Reducing form anxiety and frustration

Key Takeaway: Use :user-valid and :user-invalid instead of :valid and :invalid when you want validation styling to appear only after the user has actually interacted with a form field, creating a more forgiving and user-friendly experience.