:invalid CSS Pseudo Class

Description

The :invalid pseudo-class in CSS is a selector that targets form elements whose user input does not meet the validation criteria specified in their associated HTML attributes, such as required, pattern, or min and max values. This pseudo-class is primarily used with form elements like <input>, <textarea>, and <select>.

When a user submits a form with invalid input, the elements that fail validation will be automatically targeted by :invalid. Developers can use this pseudo-class to style or apply custom validation error messages to these elements, helping users understand and correct their input errors.

Here's an example of how you might use :invalid in CSS:

input:invalid {
border: 2px solid red; /* Apply a red border to invalid inputs */
}

input:invalid + .error-message {
display: block; /* Show an error message next to the invalid input */
color: red;
}

In this example, any <input> element that fails validation will have a red border applied, and an adjacent element with the class "error-message" will be displayed to provide feedback to the user about the validation error.

Syntax

:invalid {
  /* ... */
}

Example

<p>Input should be a url address.</p>
<input type="url">
<p>Input should be an email address.</p>
<input type="email">
<p>Input should be a number.</p>
<input type="number">
input {
background: #b4f7ab;
border: 1px solid #06bca7;
padding: 3px 10px;
}
input:invalid {
background: #fc9cac;
border: 1px solid #bc0624;
}

Browser Support

The following table will show you the current browser support for the CSS :invalid pseudo class.

Desktop
Edge Chrome Firefox Opera Safari
12124105
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview
18410.15137

Last updated by CSSPortal on: 1st October 2023