CSS :valid - Style Field when Input is Valid

The CSS :valid pseudo-class is used when we need to style FORM ELEMENTS when the user provides a valid value. For example:

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      input:valid {background-color: green; color: white;}
   </style>
</head>
<body>

   <form>
      Email ID: <input type="email"><br/>
      Enter a Number (10-50): <input type="number" min="10" max="50">
   </form>
   
</body>
</html>
Output
Email ID:
Enter a Number (10-50):

In the above example, the following CSS code:

input:valid {background-color: green; color: white;}

sets the background color to green and text color to white for any input element that is considered valid based on its type and attributes.

The CSS pseudo-class ":valid" applies to form elements that have met their validation criteria. Two input fields are included within a form element in this code. The first input field consists of

type="email"

attribute which validates whether the entered value is a properly formatted email address. The second input field has

type="number"

attribute and

min="10"

and

max="50"

attributes, which specifies the minimum and maximum range of the number.

When a user enters a value into one of these input fields, the browser checks to see if the value is valid based on the type and attributes specified. If the entered value is valid, the ":valid" pseudo-class is applied to the input element, and the background and text colors are set to green and white, respectively. If the entered value is invalid, the input element is given the ":invalid" pseudo-class instead. However, there is no CSS rule defined in this code snippet for the ":invalid" pseudo-class, so the default browser styles will be used.

In other words, when we supply the valid value in the above input fields, then the applied style can be seen. For example, if you type any number, say 10, 11, 12, ... 50, in the second field, then the style gets applied. Otherwise, on providing any number, like 1, 2, 3, etc., other than 10 to 50, the defined style will not be applied.

CSS :valid syntax

The syntax of the ":valid" pseudo-class in CSS is:

selector:valid {
   // CSS styles to be applied to the valid form element
}

In this case, "selector" refers to any valid CSS selector that selects the form element. The styles defined inside the curly braces will be applied to the form element if it is deemed valid based on its type and attributes.

Advantages of the ":valid" pseudo-class in CSS

Disadvantages of the ":valid" pseudo-class in CSS

CSS Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!