Paul Underwood
PaulundSoftware Engineer

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 pseudo class you have 2 other classes and . These two pseudo classes are used to show which inputs have validated correctly. If the input field has validated correctly then the pseudo class will be activated, if the form field is invalid the pseudo class will be activated. The pseudo-class you need to use is .


: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>