DEV Community

Cover image for Role of CSS in form validation
Kurapati Mahesh
Kurapati Mahesh

Posted on


Role of CSS in form validation

:valid selector - selects elements with a value that validates as per the element settings

:invalid selector - selects elements with a value that won't validates as per the element settings

Both works on form input elements like

  1. Input elements with min & max are applied
  2. Email type input with legal email
  3. Number fields with numeric value etc.
    * {
        box-sizing: border-box;

    .html-validation {
        margin: auto;
        width: 30%;
        border: 1px solid green;
        box-shadow: 5px 5px 8px green;
        border-radius: 5px;
        padding: 20px;

    label {
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        display: block;
        text-align: center;

    input {
        width: 100%;
        padding: 10px;
        margin: 10px 0px;
        border-radius: 10px;

    input:invalid {
        border: 1px solid red;

    input:valid {
        border: 1px solid green;

<form class="html-validation" action="#0" method="post">
        <label for="firstName">First Name</label>
        <input name="firstName" type="text" required>
        <input type="submit">
Enter fullscreen mode Exit fullscreen mode

Image description

Image description

Styles are applied as soon as the input becomes valid or invalid.

There are few other CSS selectors which does similar kind of work are:

:optional - Selects all non-required elements in form and if we apply styles using this selector then applied to all optional elements in the form.

:required - Opposite to optional and selects all required elements in the form.

:in-range - selects elements with value specified is within the range - mostly applicable for input elements with max and min specified.

:out-of-range - Opposite to in-range.

:readonly - selects elements which are specified with readonly attribute

:read-write - selects elements which are readable and writable. As such not mentioned as disabled and readonly.

:checked - Selects all checked elements. Checkboxes and radio buttons, options.

:hover - selects any element when user hovers over it

:visited - applicable for links when user clicked and visited it.

:active - selects when user selected it.

:disabled - selects all elements with attribute mentioned as disabled

:focus - Selects focused element

:empty - selects elements with no children

Top comments (3)

kimmoli profile image
Kimmo Lindholm

Related, here is a list what you want to validate for name fields

fruntend profile image

Сongratulations 🥳! Your article hit the top posts for the week -
Keep it up 👍

vidipghosh profile image
Vidip Ghosh

Very useful. Thanks a lot for sharing

Visualizing Promises and Async/Await 🤓

async await

☝️ Check out this all-time classic DEV post on visualizing Promises and Async/Await 🤓