Using The :invalid CSS Pseudo Class

With HTML5 it comes with built in features to perform form validation, one of the common attributes to use is the required attribute, this allows you to set which form inputs are required to have a value before progressing with the form.

Along with the :required pseudo class you have 2 other classes :valid and :invalid. These two pseudo classes are used to show which inputs have validated correctly. If the input field has validated correctly then the :valid pseudo class will be activated, if the form field is invalid the :invalid pseudo class will be activated.

The pseudo-class you need to use is :invalid.

:invalid {
    background-color: #ffdddd;
}
:valid {
    background-color: #ddffdd;
}

Browser Support

This class is currently supported on the following browsers.

  • Chrome 10 or higher
  • Firefox 4.0 or higher
  • IE 10
  • Opera 10
  • Safari 5.0

Example Using The Invalid Class

In this example we show how the invalid class works on a basic form.

<style type="text/css">
  :invalid {
    background-color: #ffdddd;
  }
   
  :valid {
    background-color: #ddffdd;
  }
</style>

<form>
<p><label>Username</label><input type="text" /></p>
<p><label>Email</label><input type="email" required /></p>
</form>

As you can see from this example the Email text box is highlighted red because it has a required attribute on the field and it will current fail validation.

Advertise here

Comment