CSS :invalid
Pseudo-Class
The :invalid
pseudo-class targets form elements that do not meet the required validation criteria. This is especially useful for highlighting user errors in forms, such as invalid email addresses or missing required fields.
1. Syntax
✅ Applies styles to form elements that fail validation based on their attributes, such as required
, type
, pattern
, etc.
2. Example – Styling Invalid Form Input
✅ If the email input is invalid, it will have a red border.
3. Example – Using :invalid
with required
Fields
✅ If the username input is left empty, it will turn light pink with a matching border to show the user the field is invalid.
4. Working with Different Input Types
✅ If the phone number is not in the correct format (123-456-7890
), the input will have an orange dashed border.
5. Combining :invalid
with Other Pseudo-Classes
You can use :invalid
together with other pseudo-classes for a more advanced approach.
✅ Invalid inputs that are in focus will have a red border and a shadow.
6. Using :invalid
with :valid
✅ Valid fields (correct email, phone format) will have a green border.
✅ Invalid fields will have a red border.
7. Browser Support
✅ Fully supported in all modern browsers (Chrome, Edge, Firefox, Safari, Opera).
❌ May not work with older browsers (e.g., Internet Explorer).
8. Best Practices
✔ Use :invalid
for dynamic feedback when a user submits a form or interacts with form fields.
✔ Combine :invalid
with the :valid
pseudo-class to offer visual feedback for both correct and incorrect inputs.
✔ Pair it with :focus
for real-time form error indications during user interaction.