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

:valid and :invalid for Real-Time Feedback

Apply styles based on HTML5 validation state to provide immediate user feedback without JavaScript.

:valid and :invalid for Real-Time Feedback

You'll learn how to style form inputs dynamically based on whether they meet HTML5 validation rules, giving users instant visual feedback as they type.

What Are :valid and :invalid?

These are CSS pseudo-classes that automatically apply when an input field's content passes or fails its built-in HTML5 validation constraints. Think of them as automatic traffic lights for your form fields: green when everything's okay, red when something's wrong—no JavaScript required.

When you add attributes like required, type="email", pattern, minlength, or min/max to your inputs, the browser tracks whether the current value is valid. CSS can then react to this state instantly.

How It Works

/* Style inputs that pass validation */
input:valid {
  border: 2px solid green;
  background-color: #f0fff0;
}

/* Style inputs that fail validation */
input:invalid {
  border: 2px solid red;
  background-color: #fff0f0;
}
<input type="email" required placeholder="Enter email">
<input type="number" min="1" max="10" placeholder="1-10">

As soon as the user types a valid email or a number within range, the green styling appears. If they violate the rules, the red styling shows immediately.

Avoiding Premature Feedback

Empty required fields start as :invalid, which can feel harsh. Combine with :placeholder-shown to only show error styles after the user begins typing:

input:invalid:not(:placeholder-shown) {
  border-color: red;
}

Common Use Cases

  • Email format validation
  • Required field indicators
  • Number range validation
  • Pattern matching (phone numbers, postal codes)
  • Password strength requirements

Key Takeaway: :valid and :invalid pseudo-classes provide instant, automatic styling based on HTML5 validation rules, creating responsive user feedback without any JavaScript—just CSS reacting to the browser's built-in validation state.