CSS :valid Pseudo Class

CSS :valid Pseudo Class

CSS :valid Pseudo-Class

The :valid pseudo-class in CSS applies styles to form elements (input, textarea, select) when their content is valid according to HTML validation rules.

1. Syntax

selector:valid { property: value; }

2. Example – Styling a Valid Input Field

input:valid { border: 2px solid green; background-color: #eaffea; }

✅ If the input value is valid, the border turns green, and the background changes to light green.

3. Example – Validating an Email Field

<input type="email" placeholder="Enter your email">
input:valid { border: 2px solid green; } input:invalid { border: 2px solid red; }

✅ A green border appears if the entered email is correct (e.g., user@example.com).
❌ A red border appears if it's invalid (e.g., user@com).

4. Example – Required Fields Validation

<input type="text" required placeholder="Enter your name">
input:valid { border: 2px solid blue; } input:invalid { border: 2px solid red; }

✅ The border turns blue when the field is filled correctly.
❌ The border turns red if left empty.

5. Best Practices

✔ Use :valid with :invalid for a better user experience.
✔ Combine with :focus to provide interactive feedback.
✔ Always include required, pattern, or type attributes for proper validation.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close