CSS Reference Pseudo-class

:valid

:valid is a CSS pseudo-class used to select and style form <input> elements whose values validate according to their type specified in the type attribute.

For example, email inputs (<input type="email">) whose values match a valid email address pattern.

Trivia & Notes

When a number input type (<input type="number">) is in the range of permitted values specified using the min and max attributes, then the :valid pseudo-class matches, and also the :in-range pseudo-class matches. Any styles applied using :in-range will override the styles applied using :valid only if the :in-range styles come after the :valid styles in the style sheet.

Just like other pseudo-class selectors, the :valid selector can be chained with other selectors such as :hover and :focus, among others. For example, the following rule will provide focus styles for the element that is in an valid state, adding a soft green glow around it:

input:valid:focus {
    outline: 0;
    border: none;
    box-shadow: 0 0 3px 6px rgba(0, 200, 0, 0.3);
}
                

You can see a live demo of this in the live demo section below.

Examples

input[type="number"]:valid {
    background-color: lightgreen;
}                   

input:valid {
    box-shadow: 0 0 3px 5px rgba(0, 200, 0, .2);
}
                

Live Demo

The following demo shows different input types that will get a light green background color as long as the value entered in them is valid. The inputs will also get a subtle green box shadow when they are focused.

The demo also uses the :invalid pseudo-class selector to style the inputs when the value inside them does not validate.

View this demo on the Codrops Playground

Browser Support

The :valid pseudo-class is supported in Chrome 10+, Firefox 4+, Safari 5+, Opera 10+, Internet Explorer 10+ and on iOS.

Written by . Last updated December 11, 2016 at 9:49 pm by Manoela Ilic.

Do you have a suggestion, question or want to contribute? Submit an issue.