Understanding the :valid and :invalid Pseudo-Classes in CSS
The :valid and :invalid pseudo-classes in CSS are used to style form elements based on their validation state. They apply automatically when form inputs have constraints like required, pattern, type, min, or max.
:valid – Selects form elements whose current value satisfies all HTML validation constraints.
:invalid – Selects form elements whose current value does not meet the validation requirements.
These pseudo-classes work dynamically as the user interacts with form fields, providing immediate visual feedback.
In this example, the email and password inputs will have a green border when their values are valid and a red border when invalid, giving users immediate feedback on the correctness of their input.
Use :valid and :invalid to provide real-time visual feedback on form fields, improving UX.
Combine with :focus or :hover for enhanced styling while interacting with the form.
Always pair CSS validation feedback with HTML5 validation or JavaScript for accessibility.
Test across browsers, as some older browsers may not fully support these pseudo-classes.
How would you style a required email input to turn red when the user types an invalid email, and green when it's valid, using only CSS?
What happens if you apply :invalid to a text input that has no validation attributes like required or pattern?
A form field is showing :invalid styles even though the user entered a valid phone number — what could be wrong, and how would you debug it?
Our design team wants all form errors to use a red border, but :invalid is also styling fields that haven’t been touched yet — how do you fix that without JavaScript?
You're building a dynamic form with 50+ fields that use :valid/:invalid for real-time feedback — how do you avoid performance issues or layout thrashing during user input?
How would you design a reusable form component library that correctly handles :valid/:invalid states across different input types while maintaining accessibility and consistency?
We’re migrating a legacy form system that relies on JavaScript validation to native HTML5 validation — what are the biggest risks in relying on :valid/:invalid across browsers and assistive technologies?
How would you architect a cross-team validation strategy where design, frontend, and QA teams all agree on the behavior of :valid and :invalid states, especially when legacy forms still use custom JS validation?