DEV Community

Cover image for Checking if an input is empty with CSS

Checking if an input is empty with CSS

Zell Liew 🤗 on December 18, 2018

Is it possible to know if an input is empty with only CSS? I had that question when I tried to make an autocomplete component for Learn JavaScript...
Collapse
 
rhymes profile image
rhymes • Edited

Hi Zell, great article!

This regexp should work: \s?\S+.*

it means: 1 optional space followed by at least one non space followed by whatever.

I tested it and:

  • one space = red
  • one space followed by one non space = green
  • more than one space followed by anything = red
  • spaces between chars = green
Collapse
 
zellwk profile image
Zell Liew 🤗

Thanks!

Collapse
 
ben profile image
Ben Halpern

Damn this is good CSS stuff. Awesome post Zell.

Collapse
 
zellwk profile image
Zell Liew 🤗

Thank you!

Collapse
 
pipobscure profile image
Pip Obscure™️ • Edited

Try pattern=“\S+“ which means has to contain 1 or more non-white-space characters

Collapse
 
lexlohr profile image
Alex Lohr

Since pattern works like new RegExp('^'+pattern+'$'), this won't work if there are white-space characters in the input value.

Collapse
 
kateika profile image
kateika

thanks for great investigation! Could you please reveal browser support for this method?)

Collapse
 
ewbi profile image
ewbi
Collapse
 
joshichinmay profile image
Chinmay Joshi

This is pretty cool. Thanks for sharing Zell. :)