CSS :invalid | Style FORM INPUT fields having invalid inputs or values

The CSS :invalid pseudo-class is used when we need to select and style a FORM field with invalid inputs. For example:

HTML with CSS Code
<!DOCTYPE html>
      input:invalid {color: red;}

      Enter Email ID: <input type="email"><br/>
      Enter a Number: <input type="number" min="10" max="100">

Enter Email ID:
Enter a Number:

This example defines a CSS rule that selects and styles any form input fields that have failed validation by using the :invalid pseudo-class. The rule changes the input field's text color to red.

Two input fields are contained within a form element in the HTML code. The type attribute of the first input field is set to email, indicating that it should accept an email address as input. The second input field has the type attribute set to number and the min and max attributes specifying the minimum and maximum values.

If a user enters invalid data into either of these input fields (for example, an incorrectly formatted email address or a number outside the specified range), the input field will be marked as invalid and will match the CSS rule defined in the style element. The text color of the input field will be changed to red to indicate an error.

For example, if a user enters an email address into the first input field without including the @ symbol, the input field will be marked as invalid and its text color will be changed to red. Similarly, if a user enters a number less than 10 or greater than 100 into the second input field, it is marked as invalid and the text color is changed to red.

Therefore, in short, when a user enters an invalid email address, the color of the entered value changes to red. Similarly, for the second FORM field, if the user enters a value less than 10 or greater than 100, the number will turn red.

CSS :invalid syntax

The syntax of the ":invalid" pseudo-class is:

input:invalid {
   // CSS styles to apply when the input is invalid

In the preceding syntax, "input" refers to the form element to which we want to apply the styles, and ":invalid" is the pseudo-class that targets that element's invalid input. Depending on which element we want to style, we can replace input with other form elements such as textarea, select, and so on.

Advantages of the ":invalid" class in CSS

Disadvantages of the ":invalid" class in CSS

CSS Online Test

« Previous Tutorial Next Tutorial »

Liked this post? Share it!