CSS :invalid Selector

Beginner
⏱️ 7 min read
📚 Updated: Jul 2026
🎯 4 Examples
Form Validation

What You’ll Learn

The :invalid pseudo-class styles form fields whose values fail validation rules. It provides instant visual feedback during data entry.

01

Failed rules

Bad input.

02

required

Empty fields.

03

type & pattern

Email, regex.

04

:valid

Success pair.

05

Real-time

Live feedback.

06

HTML5

No JS needed.

Introduction

The :invalid selector in CSS is used to select form elements whose values fail to meet validation criteria. It is especially useful for styling inputs with incorrect or incomplete data based on type, pattern, required, or range constraints.

This selector helps enhance form usability and provides visual feedback to users as they type.

Definition and Usage

Use :invalid on its own or scoped to elements: input:invalid, textarea:invalid, or input[type="email"]:invalid. Styles apply while the field’s value does not satisfy its validation constraints.

💡
Beginner Tip

Pair :invalid with :valid for red/green feedback. To avoid showing errors on empty fields before the user types, use input:invalid:not(:placeholder-shown) or input:invalid:focus.

📝 Syntax

The syntax for the :invalid pseudo-class is:

syntax.css
:invalid {
  /* CSS properties */
}

The :invalid selector applies to <input>, <textarea>, and <select> elements with built-in validation rules.

Basic Example

invalid-basic.css
:invalid {
  border: 2px solid #dc2626;
  background-color: #fef2f2;
}

:valid {
  border: 2px solid #16a34a;
  background-color: #f0fdf4;
}
input:invalid input[type="email"]:invalid :valid form:has(:invalid)

Common Validation Triggers

AttributeWhat makes input :invalid
requiredField is empty
type="email"Value is not a valid email format
patternValue does not match the regex
min / maxNumber or date is out of range
minlength / maxlengthText is too short or too long

Syntax Rules

  • Inputs need validation constraints (required, type, pattern, etc.) for meaningful :invalid matching.
  • Empty required fields often match :invalid immediately on page load.
  • Scope with element selectors: input:invalid avoids styling unrelated elements.
  • Pair with :valid for complete positive/negative feedback.
  • Always validate on the server — CSS is for UX only, not security.

Related Selectors

  • :valid — matches inputs that pass all validation rules
  • :in-range — value within min/max only (narrower than :invalid)
  • :out-of-range — value outside min/max only
  • :required — matches fields with the required attribute
  • :focus — combine to show errors only while editing

⚡ Quick Reference

QuestionAnswer
Selector typePseudo-class (UI state / validation)
When it appliesValue fails HTML5 validation constraints
Best paired with:valid
Delay errors until typed:invalid:not(:placeholder-shown)
Common propertiesborder, background-color, box-shadow
Browser supportAll modern browsers

When to Use :invalid

:invalid improves form UX with real-time validation feedback:

  • Registration forms — Highlight invalid email, password, or username fields instantly.
  • Required fields — Show red styling when mandatory inputs are empty or incomplete.
  • Pattern matching — Flag phone numbers or zip codes that don’t match pattern.
  • Numeric limits — Indicate age or quantity values that fail min/max rules.
  • Multi-step wizards — Visually mark steps with invalid fields before allowing progression.

👀 Live Preview

Try entering an invalid email or age outside 18–65. Valid values turn green; invalid values turn red:

Examples Gallery

Practice :invalid with email forms, scoped inputs, delayed error display, and pattern validation.

📜 Core Patterns

Style form fields that fail HTML5 validation.

Example 1 — Basic :invalid and :valid styling

Apply red styling to invalid fields and green to valid ones in a registration form.

invalid-form.html
<style>
  :invalid {
    border: 2px solid #dc2626;
    background: #fef2f2;
  }
  :valid {
    border: 2px solid #16a34a;
    background: #f0fdf4;
  }
  input {
    padding: 0.5rem;
    border-radius: 0.4rem;
    width: 100%;
  }
</style>

<form>
  <label for="email">Email:</label>
  <input type="email" id="email" required>

  <label for="age">Age (18–65):</label>
  <input type="number" id="age" min="18" max="65" required>
</form>
Try It Yourself

How It Works

Invalid email format or empty required fields match :invalid (red). Correct values match :valid (green).

Example 2 — Scoped email validation

Target only email inputs with a red box-shadow on invalid state.

invalid-email.css
input[type="email"]:invalid {
  border-color: #dc2626;
  background: #fef2f2;
  box-shadow: 0 0 0 3px rgba(220, 38, 38, 0.2);
}

input[type="email"]:valid {
  border-color: #16a34a;
  background: #f0fdf4;
}
Try It Yourself

How It Works

Scoping to input[type="email"] ensures only email fields get validation styling, leaving other inputs unaffected.

📄 UX Patterns

Improve validation UX with delayed and pattern-based rules.

Example 3 — Show errors only after user types

Avoid red borders on empty fields at page load using :not(:placeholder-shown).

invalid-delayed.css
input:invalid:not(:placeholder-shown) {
  border-color: #dc2626;
  background: #fef2f2;
}

input:valid {
  border-color: #16a34a;
  background: #f0fdf4;
}
Try It Yourself

How It Works

While the placeholder is visible (field empty), :not(:placeholder-shown) prevents the invalid style. Once the user types, validation feedback kicks in.

Example 4 — Pattern validation for phone number

Use the pattern attribute with :invalid to validate a specific format.

invalid-pattern.html
<style>
  input:invalid {
    border-color: #dc2626;
  }
  input:valid {
    border-color: #16a34a;
  }
</style>

<label for="phone">Phone (10 digits):</label>
<input type="tel" id="phone"
  pattern="[0-9]{10}" placeholder="1234567890" required>
Try It Yourself

How It Works

The pattern="[0-9]{10}" attribute enforces exactly 10 digits. Values that don’t match trigger :invalid styling.

💬 Usage Tips

  • HTML5 attributes — Works with required, type, pattern, min, max, and length constraints.
  • Pair with :valid — Give users positive feedback when they correct mistakes.
  • Scope selectors — Use input:invalid instead of bare :invalid when possible.
  • Delay initial errors — Use :invalid:not(:placeholder-shown) to avoid red empty fields on load.
  • Server validation — CSS validation is cosmetic; always validate on the server.

⚠️ Common Pitfalls

  • No validation rules — Without required, type, or pattern, :invalid has little effect.
  • Red fields on page load — Empty required inputs match :invalid immediately; delay with placeholder-shown trick.
  • Browser default UI — Native tooltips and bubbles may clash with custom styles; test across browsers.
  • Custom JS validation — JavaScript validation libraries may bypass native :invalid matching.
  • Security — Never rely on CSS or client-side validation alone for data integrity.

♿ Accessibility

  • Do not rely on color alone — Pair red borders with text error messages linked via aria-describedby.
  • Associate labels — Every input needs a <label> so screen readers announce the field name.
  • aria-invalid — Set aria-invalid="true" on invalid fields for assistive technology (often via JS).
  • Clear error text — Explain what is wrong (“Enter a valid email”) not just that the field is red.
  • Contrast — Error borders and backgrounds must meet WCAG contrast requirements.

🧠 How :invalid Works

1

HTML defines rules

Attributes like required, type="email", or pattern set constraints.

HTML
2

Browser validates value

On input or submit, the browser checks the value against all constraints.

Check
3

:invalid matches

If any rule fails, the element matches :invalid and CSS applies.

Style
=

Instant error feedback

Users see immediately that their input needs fixing.

🖥 Browser Compatibility

The :invalid pseudo-class is supported in all modern browsers.

Baseline · Universal support

Form validation styling everywhere

:invalid works in Chrome, Firefox, Safari, Edge, and Opera.

99% Universal support
Google Chrome 10+ · Desktop & Mobile
Full support
Mozilla Firefox 4+ · Desktop & Mobile
Full support
Apple Safari 5+ · macOS & iOS
Full support
Microsoft Edge 12+
Full support
Opera 11+
Full support
:invalid pseudo-class 99% supported

Bottom line: :invalid is safe for modern form validation UI. Always validate on the server too.

🎉 Conclusion

The :invalid selector is a key component of modern form design, allowing developers to provide instant feedback when users enter invalid data.

Pair it with :valid, use the placeholder-shown trick to avoid premature errors, and always back up client-side styling with server-side validation and accessible error messages.

💡 Best Practices

✅ Do

  • Pair :invalid with :valid
  • Use HTML5 validation attributes
  • Delay errors with :not(:placeholder-shown)
  • Provide text error messages alongside colors
  • Validate on the server as well

❌ Don’t

  • Rely on CSS alone for security
  • Show red borders on all empty fields at load
  • Depend on color alone for errors
  • Forget labels and aria-invalid
  • Skip cross-browser testing

Key Takeaways

Knowledge Unlocked

Five things to remember about :invalid

Use these points when styling failed validation.

5
Core concepts
req 02

HTML5 attrs

required, type.

Trigger
03

:valid pair

Green success.

Tip
:ps 04

Delay errors

placeholder-shown.

UX
🌐 05

99% support

All browsers.

Compat

❓ Frequently Asked Questions

The :invalid pseudo-class matches form elements whose current value fails HTML5 validation rules — such as an empty required field, a malformed email, or a number outside min/max.
Common triggers include required, type (email, url, number, etc.), pattern, min, max, minlength, maxlength, and step. The input must have at least one constraint for :invalid to apply meaningfully.
:invalid is broader — it covers any validation failure including empty required fields and bad email format. :out-of-range only checks whether a numeric or date value is outside min/max.
Yes. Use :invalid for error styling (red border) and :valid for success styling (green border) so users get clear feedback when they fix their input.
:invalid is supported in all modern browsers. Note that empty required fields may match :invalid immediately on page load — consider :focus or :not(:placeholder-shown) to delay error styling.

Practice in the Live Editor

Open the HTML editor and experiment with :invalid, :valid, and form validation styling.

HTML Editor →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful