CSS :invalid
The CSS :invalid pseudo-class targets form elements whose input data does not satisfy the validation constraints set by their attributes, such as required, pattern, type, or minlength. It is useful for styling elements that contain invalid data to provide visual feedback to users.
The syntax for the :invalid pseudo-class is:
selector:invalid {
property: value;
}
Where:
| Parameter | Description |
|---|---|
selector | The form element (e.g., <input>, <textarea>) to which the :invalid pseudo-class will apply. |
property | The CSS property to style the invalid element. |
value | The value assigned to the CSS property. |
Examples
1. Styling Invalid Email Inputs
In this example, invalid email input fields are styled with a red border.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
input:invalid {
border: 2px solid red;
}
input:valid {
border: 2px solid green;
}
</style>
</head>
<body>
<form>
<label>Email:</label>
<input type="email" placeholder="Enter your email" required>
</form>
</body>
</html>
2. Styling Invalid Number Inputs
Here, invalid number input fields (e.g., outside a specified range) are styled with a pink background.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
input:invalid {
background-color: lightpink;
}
input:valid {
background-color: lightgreen;
}
</style>
</head>
<body>
<form>
<label>Enter a number (1-10):</label>
<input type="number" min="1" max="10" required>
</form>
</body>
</html>
3. Styling Invalid Password Inputs
In this example, invalid password inputs (e.g., not meeting the minlength requirement) are styled with red text.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
input:invalid {
color: red;
}
input:valid {
color: green;
}
</style>
</head>
<body>
<form>
<label>Password (min 6 characters):</label>
<input type="password" minlength="6" required>
</form>
</body>
</html>
4. Styling Invalid Textareas
Here, invalid textareas (e.g., not meeting a minimum character requirement) are styled with a yellow border.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
textarea:invalid {
border: 2px solid yellow;
}
textarea:valid {
border: 2px solid green;
}
</style>
</head>
<body>
<form>
<label>Comment (min 10 characters):</label>
<textarea minlength="10" required></textarea>
</form>
</body>
</html>
5. Styling Invalid Select Dropdowns
In this example, invalid <select> dropdowns (e.g., not selecting an option) are styled with a red outline.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
select:invalid {
border: 2px solid red;
}
select:valid {
border: 2px solid green;
}
</style>
</head>
<body>
<form>
<label>Choose an option:</label>
<select required>
<option value="">Select one</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
</form>
</body>
</html>
