DEV Community

t-o-d
t-o-d

Posted on

Three main useful techniques to check input forms using only CSS

Technique1 : Blank check for input form

Using the 「placeholder-shown」 attribute

Result

Details

  • The attribute used in the CSS part of this input form is placeholder-shown.
  • This indicates when a placeholder is displayed.
  • In other words, by using 「not」 in the following specification, we can make the button clickable by increasing the transparency of the button when the placeholder is not displayed.
<input placeholder="Please enter a value.">
<button>save</button>
/*
Use opacity to reduce the initial transparency by half.
By using pointer-events, the initial button click is disabled.
*/
button {
    opacity: 0.5;
    pointer-events: none;
}

/*
Using not(:placeholder-shown), you can use
If you don't see the placeholder, you can use
Automatic setting of pointer-events.
Restore the opacity's transparency as well.
*/
input:not(:placeholder-shown) + button {
    opacity: 1;
    pointer-events: auto;
}

Technique2 : Check the format of the input form

Using the 「valid and invalid」 attribute

Result

Details

  • In the CSS part of this input form, I'm using invalid and valid as attributes.
  • This indicates if the form matches the type specified in the input tag's type attribute (valid) or not (invalid).
  • In other words, the following specification will change the background color depending on whether the input value matches the format.
<input type="email" placeholder="Enter email address">
<button>save</button>
/*
Using the invalid attribute, the
The background color if the type attribute format does apply.
*/
input:invalid {
  background-color: #ee6666;
}

/*
Using the valid attribute, the
The background color if the type attribute format does not apply.
*/
input:valid {
  background-color: #95f195;
}

Technique3 : Check the scope of the input form

Using the 「in-range and out-of-range」 attribute

Result

Details

  • The CSS parts of this input form use 「in-range」 and 「out-of-range」 attributes.
  • This indicates if the range of values specified in the input tag's min and max attributes is met (in-range) or not (out-of-range).
  • In other words, the following specification will mean that the background color will be changed depending on whether the input value is beyond the specified numerical range.
<input type="number" min="1" max="20">
<button>save</button>
/*
Using the in-range attribute, the
The background color if it falls within a range of values.
*/
input:in-range {
  background-color: #95f195;
}
/*
Using the out-of-range attribute, you can use the
Background color if the value does not fall within a range of values.
*/
input:out-of-range {
  background-color: #ee6666;
}

Link

Top comments (0)