The :invalid
pseudo-class selects form elements whose content does not validate against their type or constraints. This is crucial for creating user-friendly forms that guide users in correcting their mistakes.
Example 1: Red Border for Invalid Input
/* This CSS rule targets an input with invalid content. */
input:invalid {
/* The border-color is set to red. */
border-color: red;
}
Explanation
This is a common and effective way to show that a field is invalid. The red border immediately draws the user's attention to the field that needs correction.
Example 2: Displaying an Error Message
/* This CSS rule targets a span with the .error-message class next to an invalid input. */
input:invalid ~ .error-message {
/* The display property is set to block to show the message. */
display: block;
/* The color is set to red. */
color: red;
}
Explanation
This example shows an error message (which is initially hidden) when an input field is invalid. The general sibling combinator (~
) is used to select the error message element.
Example 3: Shaking Animation for Invalid Fields
/* This defines a keyframe animation for shaking. */
@keyframes shake {
0%, 100% { transform: translateX(0); }
25% { transform: translateX(-5px); }
75% { transform: translateX(5px); }
}
/* This applies the animation to invalid inputs. */
input:invalid {
animation: shake 0.2s;
}
Explanation
This more advanced example uses a CSS animation to make an invalid input field "shake" when the user input is incorrect, providing a very noticeable cue for correction.
Example 4: Invalid Input with an Icon
/* This CSS positions a pseudo-element after an invalid input. */
input:invalid + .invalid-icon::after {
/* The content property adds a cross character. */
content: '✗';
/* The color is set to red. */
color: red;
}
Explanation
Similar to the valid icon example, this displays a red "X" next to an input field when its content is invalid, offering immediate and clear feedback.
Example 5: Disabling Submit Button When a Field is Invalid
/* This CSS rule disables the submit button if any required field is invalid. */
form:invalid input[type="submit"] {
opacity: 0.5;
pointer-events: none;
}
Explanation
This powerful technique prevents a form from being submitted if any of its required fields are invalid. It works by targeting the submit button within a form that is in an :invalid
state.