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

:in-range and :out-of-range for Form Validation

Style numeric and date inputs based on whether their values fall within the min and max constraints.

:in-range and :out-of-range for Form Validation

You'll learn how to visually indicate when numeric or date inputs meet or violate their min/max constraints.

What Are These Selectors?

When you add min and max attributes to numeric (<input type="number">) or date-related inputs (date, datetime-local, time, month, week), CSS automatically tracks whether the user's entry falls within that valid range. The :in-range pseudo-class matches inputs with valid values, while :out-of-range targets inputs with values outside the allowed bounds.

Think of it like a bouncer at a club checking age: people within the age range get a green wristband (:in-range), while those too young or too old get a red one (:out-of-range).

How It Works

input:in-range {
  border: 2px solid green;
  background-color: #e8f5e9;
}

input:out-of-range {
  border: 2px solid red;
  background-color: #ffebee;
}
<label>Age (18-65):
  <input type="number" min="18" max="65" value="25">
</label>

<label>Appointment Date:
  <input type="date" min="2024-01-01" max="2024-12-31">
</label>

As soon as a user types "70" in the age field, the input automatically receives the :out-of-range styling. Change it back to "30" and it switches to :in-range styling—no JavaScript required.

Important Notes

These pseudo-classes only apply to inputs with min and max constraints. Empty inputs or inputs without these attributes won't match either selector.

Key Takeaway: Use :in-range and :out-of-range to provide instant visual feedback on constrained numeric and date inputs, making form validation more intuitive for users.