
Is it possible to tell whether an input is empty with nothing but CSS and HTML?
In this tutorial I will show you a few tricks for checking whether an input is valid or not with CSS and HTML alone. It is not something to rely on by itself, but rather alongside a PHP validation, and it stays an interesting alternative if you would rather not bother with JavaScript.
Checking whether the input is empty
First, let us build a form. We will use a simple form with a single input, and to check whether that input is empty during the HTML form validation I add the required attribute.
<form>
<label> Input </label>
<input type="text" name="input" id="input" required />
</form>Nothing complicated so far, the required attribute is well known. There is also readonly, which stops a default value from being changed.
At this point there is a problem: if the user types a space in the field, the input is “filled in”. Technically that is correct, the input is filled because the user typed something into it, but we do not want whitespace to make the input valid.
That is not enough, so we need a stricter check.
Further checks
HTML lets you validate inputs with regular expressions, through the pattern attribute.
Since we do not want whitespace to count, we will try the following pattern: .*S.*. It reads as: one or more characters that are not spaces.
<form>
<label> Input </label>
<input type="text" name="input" id="input" required pattern=".*S.*"/>
</form>Invalid inputs
We do not want to use :invalid, because we are not going to start the input in an invalid state. (When the input is empty, it is already invalid.)
There is a :placeholder-shown pseudo-class that tells you whether the placeholder is on screen. The idea is:
- You type a character into your field
- If the placeholder is hidden, the user has typed something into the field
- Carry on with the validation (or the invalidation)
/* Afficher les bordures rouges lorsqu'elles sont remplies, mais non valides */
input:not(:placeholder-shown) {
border-color: red;
}Do make sure that the valid styles come after the invalid ones.
/* Afficher les bordures rouges lorsqu'elles sont remplies, mais non valides */
input:not(:placeholder-shown) {
border-color: hsl(0, 76%, 50%);;
}
/* Afficher les bordures vertes lorsqu'elles sont valides */
input:valid {
border-color: green;
}Careful: Edge does not support :placeholder-shown, so it is probably not a good idea to use it in production just yet. And there is no good way to feature-detect this pseudo-class.


