W3docs

CSS :invalid Pseudo Class

The :invalid CSS pseudo-class selects the elements with a value that is invalid according to the settings of the element. Read about the pseudo-class and try examples.

The CSS :invalid pseudo-class selects form-associated controls (such as <input>, <select>, and <textarea>) with a value that is invalid according to their settings.

The :invalid selector applies to form elements with validation constraints, such as <input> fields with min and max attributes (for number, range, and date types), email fields without a valid email address, number fields without a numeric value, or required fields with an empty value.

Notes

Radio buttons

When one of the radio buttons in a group is required, the :invalid selector is applied to all of them (if all the buttons in the group are not selected). Grouped radio buttons have the same value for their name attribute.

Gecko defaults

By default, Gecko does not apply a style to the :invalid pseudo-class (however, we can apply a red "glow" with the box-shadow property) but applies style to the :-moz-ui-invalid pseudo-class, which applies in a subset of cases for :invalid pseudo-class.

Complementary pseudo-class

For contrast, the :valid pseudo-class selects form controls that pass their validation constraints.

Version

Selectors Level 4

Syntax

CSS :invalid syntax code

:invalid {
  css declarations;
}

Example of the :invalid selector:

CSS :invalid code example

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      input:invalid {
        border: 2px solid #ff0000;
      }
    </style>
  </head>
  <body>
    <h2>:invalid selector example</h2>
    <form>
      <input type="email" value="invalid-email" required />
    </form>
  </body>
</html>

Practice

Practice

What is the function of the ':invalid' pseudo-class in CSS?