Open In App

CSS :invalid Selector

Last Updated : 29 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

This :invalid selector is used to select every form elements which does not validate according to the elements. This selector works only for some form elements with limitations such as input elements with min and max attributes, email fields with a legal email, or number fields with a numeric value, etc. Instead of using the :invalid selector, the :valid selector is used to selects the form elements which validate according to the element. 

Syntax:

:invalid {
// CSS property
}

Example: 

html
<!DOCTYPE html>
<html>

<head>
    <title>invalid selector</title>
    <style>
        h1 {
            color:green;
        }
        input:invalid {
            border: 1px solid black;
            border-radius:4px;
            color:white;
            background-color:green;
            padding:5px;
        }
        body {
            text-align:center;
        }
    </style>
</head>

<body>
    <h1>GeeksforGeeks</h1>
    <h2>:invalid Selector</h2>
    Email Address: 
    <input type="email" 
        placeholder="abc@gfg.com">
</body>

</html>

Output:

 

Supported Browsers: The browser supported by :invalid selector are listed below:

  • Apple Safari 5.0
  • Google Chrome 10.0
  • Edge 12.0
  • Firefox 4.0
  • Opera 10.0

CSS :invalid Selector – FAQs

What does the :invalid selector do in CSS?

The :invalid selector targets input elements that are in an invalid state, such as when their value does not meet specified constraints like pattern, min, or max.

How do I style an input field when its value is invalid?

Use the :invalid selector, like input:invalid { border-color: red; }, to style input fields with invalid values.

Does :invalid apply to all form controls?

The :invalid selector applies to form controls that can have validation constraints, such as input, textarea, and select.

Can JavaScript be used to trigger the :invalid state?

Yes, JavaScript can dynamically change the attributes or values of form controls to trigger the :invalid state.

Is the :invalid selector widely supported across browsers?

Yes, the :invalid selector is supported by all modern browsers.


Next Article

Similar Reads

three90RightbarBannerImg
  翻译: