DEV Community

HidetoshiYanagisawa
HidetoshiYanagisawa

Posted on

Power Up Your CSS! Visualizing Form Validation with :has() Selector

Table of Contents

  1. Introduction
  2. Understanding the CSS :has() Pseudo-class
  3. Visualizing Form Validation
  4. Points to Note
  5. Conclusion

1. Introduction

In the realm of web development, form validation plays a critical role. It ensures that user input adheres to expected formats, thereby preventing the submission of improper data. Providing visual feedback on these validation results can enhance user experience.

In this article, we will demonstrate how to visualize form validation results using the CSS :has() pseudo-class.

2. Understanding the CSS :has() Pseudo-class

The :has() is a pseudo-class in CSS that matches if any of the selectors it is passed as parameters match at least one element.

a:has(> img) {
  border: 1px solid black;
}
Enter fullscreen mode Exit fullscreen mode

In the example above, the <a> tags that directly contain an <img> tag as a child will be selected and applied with a black border.

3. Visualizing Form Validation

We can use the following CSS code to visualize the validation results of <input> elements within an HTML <form> element.

form:has(input:invalid) {
     background: red; 
}

form:not(:has(input:invalid)) {
     background: green 
}
Enter fullscreen mode Exit fullscreen mode
  1. form:has(input:invalid): This selector matches any <form> element that contains an invalid (i.e., not conforming to the validation rules) <input> element. If a match is found, the background color of that <form> element is set to red.
  2. form:not(:has(input:invalid)): This selector matches any <form> element that does not contain any invalid <input> elements, i.e., all <input> elements are valid and conform to the validation rules. If a match is found, the background color of that <form> element is set to green.

4. Points to Note

This code uses the :has() pseudo-class, so it will only work in browsers that support this selector. Furthermore, the validation rules are defined by the attributes of the <input> elements (such as required, pattern, etc.).

5. Conclusion

By utilizing the CSS :has() pseudo-class, you can provide visual feedback when a user inputs invalid data into a form, thereby contributing to an enhanced user experience. However, it's crucial to check the browser compatibility of the :has() pseudo-class and set up appropriate validation rules.

Top comments (0)