Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Style all elements with an invalid value with CSS
To style all elements with an invalid value, use the CSS :invalid pseudo-class selector. This selector targets form elements that contain invalid data based on their type, pattern, or required attributes.
Syntax
selector:invalid {
property: value;
}
How It Works
The :invalid pseudo-class automatically applies styles to form elements when their values don't meet validation criteria. This includes invalid email formats, numbers outside specified ranges, or empty required fields.
Example: Invalid Email Input
The following example styles an email input with a red background when the email format 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;
}
label {
display: block;
margin: 10px 0 5px 0;
}
</style>
</head>
<body>
<h2>Form Validation Example</h2>
<label for="email">Email Address:</label>
<input type="email" id="email" value="InvalidEmail" placeholder="Enter your email">
<label for="number">Age (18-65):</label>
<input type="number" id="number" min="18" max="65" value="150">
<label for="required">Required Field:</label>
<input type="text" id="required" required>
</body>
</html>
Three input fields appear on the page. The email field with "InvalidEmail" shows a red background and border (invalid email format). The number field with value "150" shows red styling (outside the 18-65 range). The empty required field shows red styling. Valid inputs will display with green background and border.
Common Use Cases
The :invalid selector works with various input types and validation attributes:
- Email inputs - Invalid email format
- Number inputs - Values outside min/max range
- Required fields - Empty required inputs
- Pattern matching - Text that doesn't match specified patterns
Conclusion
The :invalid pseudo-class provides an effective way to style form elements with invalid values, improving user experience by providing immediate visual feedback. Combine it with :valid for comprehensive form styling.
