The :valid
pseudo-class selects form elements whose content validates according to their type and other constraints, such as the pattern
or required
attributes. It is useful for providing immediate feedback on correct user input.
Example 1: Green Border for Valid Email Input
/* This CSS rule targets an email input with valid content. */
input[type="email"]:valid {
/* The border-color is set to green. */
border-color: green;
}
Explanation
When a user enters a correctly formatted email address into an input with type="email"
, this CSS will apply a green border, indicating the input is valid.
Example 2: Showing a "Valid" Icon
/* This CSS rule positions a pseudo-element after a valid input. */
input:valid + .valid-icon::after {
/* The content property adds a checkmark character. */
content: '✓';
/* The color property sets the checkmark color to green. */
color: green;
}
Explanation
This example uses a pseudo-element to display a green checkmark next to a form field as soon as its content becomes valid, offering clear, positive reinforcement.
Example 3: Styling the Label of a Valid Input
/* This CSS rule targets the label of a valid input. */
input:valid + label {
/* The color property is set to green. */
color: green;
}
Explanation
This code changes the color of a label to green when the associated input field contains valid data. This provides another layer of visual feedback for the user.
Example 4: Valid Password Confirmation
/* This CSS rule targets a password input that meets a pattern requirement. */
input[type="password"]:valid {
/* A subtle green box-shadow is applied. */
box-shadow: 0 0 5px 1px rgba(0, 255, 0, 0.5);
}
Explanation
If a password field has a pattern
attribute (e.g., requiring a certain length and character types), this CSS will apply a green glow when the entered password is valid.
Example 5: Valid URL Input Highlighting
/* This CSS rule targets a URL input with valid content. */
input[type="url"]:valid {
/* The background-color is changed to a very light green. */
background-color: #e8f5e9;
}
Explanation
This CSS provides a subtle background color change for a URL input field once a valid URL format is entered.