Role of CSS :invalid Selector

The CSS :invalid pseudo-class selector targets form elements that fail validation constraints. It automatically applies styles to input fields when their values don't meet the specified requirements, providing immediate visual feedback to users.

Syntax

selector:invalid {
    property: value;
}

Example: Email Validation Styling

The following example applies a red background to an email input when the value is invalid −

<!DOCTYPE html>
<html>
<head>
<style>
    input:invalid {
        background-color: #ffcccc;
        border: 2px solid red;
    }
    
    input:valid {
        background-color: #ccffcc;
        border: 2px solid green;
    }
    
    .form-group {
        margin: 20px 0;
    }
    
    label {
        display: block;
        margin-bottom: 5px;
        font-weight: bold;
    }
</style>
</head>
<body>
    <h2>Form Validation with :invalid Selector</h2>
    
    <div class="form-group">
        <label for="email">Email Address:</label>
        <input type="email" id="email" value="InvalidEmail" required>
    </div>
    
    <div class="form-group">
        <label for="url">Website URL:</label>
        <input type="url" id="url" value="not-a-url" required>
    </div>
    
    <div class="form-group">
        <label for="number">Number (1-10):</label>
        <input type="number" id="number" min="1" max="10" value="15" required>
    </div>
</body>
</html>
Three input fields appear with red backgrounds and borders because they contain invalid values. The email field shows "InvalidEmail" (not a valid email), the URL field shows "not-a-url" (not a valid URL), and the number field shows "15" (outside the 1-10 range).

Common Use Cases

The :invalid selector works with various input validation scenarios:

  • Email validationtype="email"
  • URL validationtype="url"
  • Number rangesmin and max attributes
  • Required fieldsrequired attribute
  • Pattern matchingpattern attribute with regex

Conclusion

The :invalid selector provides automatic visual feedback for form validation without JavaScript. It enhances user experience by clearly indicating which fields need correction.

Updated on: 2026-03-15T12:19:51+05:30

281 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements