CSS :invalid Pseudo Class

CSS :invalid Pseudo Class

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

selector:invalid { /* Styles for invalid elements */ }

Applies styles to form elements that fail validation based on their attributes, such as required, type, pattern, etc.

2. Example – Styling Invalid Form Input

<form> <label for="email">Email:</label> <input type="email" id="email" required> <button type="submit">Submit</button> </form>
input:invalid { border: 2px solid red; }

✅ If the email input is invalid, it will have a red border.

3. Example – Using :invalid with required Fields

<form> <label for="username">Username:</label> <input type="text" id="username" required> <button type="submit">Submit</button> </form>
input:invalid { background-color: #f8d7da; border: 1px solid #f5c6cb; }

✅ 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

<form> <label for="phone">Phone Number:</label> <input type="tel" id="phone" pattern="\d{3}-\d{3}-\d{4}" required> <button type="submit">Submit</button> </form>
input:invalid { border: 2px dashed orange; }

✅ 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.

input:invalid:focus { border-color: #ff6347; box-shadow: 0 0 5px #ff6347; }

Invalid inputs that are in focus will have a red border and a shadow.

6. Using :invalid with :valid

input:valid { border-color: green; } input:invalid { border-color: red; }

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.

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