Last updated on

The :valid selector allows you to select <input> elements that do not contain valid content, as determined by its type attribute. :valid is defined in the CSS Selectors Level 3 spec as a “validity pseudo-selector”, meaning it is used to style interactive elements based on an evaluation of user input.

This selector has one particular use: providing a user with feedback while they are interacting with a form on the page. The example below uses CSS to turn the “Email” fields red or green, responding to the whether or not the contents match a valid email address pattern:

<label for="email">Email:</label>
<input type="email" id="email" name="email" />

<label for="emailRequired">Email (required):</label>
<input type="email" id="emailRequired" name="emailRequired" required />

<form action="#">
  <label id="guess">Enter a number 1 through 9:</label>
  <input type="text" id="guess" name="guess" pattern="[1-9]{1}" required />
</form>
input:invalid {
  background: hsla(0, 90%, 70%, 1);
}

input:valid {
  background: hsla(100, 90%, 70%, 1);
}


body {
  padding: 3em;
}
label {
  display: block;
}
input {
  padding: 0.25em 0;
  margin-bottom: 0.75em;
}

Note how the first <input> (“Email”) is green—valid—even when there is no content in the field. This is because the input is optional, so leaving it blank would result in a valid form submission. To fix this behaviour, the second <input> has a “required” attribute, which means that a blank field would result in an invalid form submission.

Points of Interest

  • :valid can be “chained” with other pseudo-selectors: like :focus to only validate when the user is typing, :before or :after to generate icons or text to provide more user feedback, or attribute selectors like input[value=""] to only validate input fields containing content.

Browser Support

Chrome Safari Firefox Opera IE Android iOS
10.0+ 5.0+ 4.0+ 10.0+ 10+ 5+ 2+

:valid was introduced in CSS Selectors Module 3, which means old versions of browsers do not support it. However, modern browser support is getting better. If you require older browser support, either polyfill, or use these selectors in non-critical ways á la progressive enhancement, which is recommended.

Leave a Reply

Your email address will not be published. Required fields are marked *