How to check if an input is empty with CSS

It can be used to check whether a placeholder is shown.The idea is:You add a placeholder to your inputIf the input is hidden, it means the user typed something into the fieldProceed with validation (or invalidation)Here’s the CSS (simplified version. For the complete version, check out Chris’s article.)/* Show red borders when filled, but invalid */input:not(:placeholder-shown) { border-color: hsl(0, 76%, 50%);}Since I had both validation AND invalidation styles, I had to ensure the valid styles came after the invalid styles./* Show red borders when filled, but invalid */input:not(:placeholder-shown) { border-color: hsl(0, 76%, 50%);;}/* Show green borders when valid */input:valid { border-color: hsl(120, 76%, 50%);}Here’s a demo for you to play with:See the Pen Pure CSS Empty validation by Zell Liew (@zellwk) on CodePen.Note: Edge doesn’t support :placeholder-shown, so it’s probably not a good idea to use it in production yet..There’s no good way to detect this feature.Now back to the problem I couldn’t resolve.The problem with patternThe pattern attribute is wonderful because it lets you accept a regular expression..This regular expression lets you validate the input with anything you can think of.But… the regular expression must match the text completely..If the text doesn’t get matched completely, the input gets invalidated.This created the problem I mentioned above..(Reminder of the problem: If a user enters a whitespace first, the input becomes invalid).I couldn’t find a regular expression that worked for all use-cases that I thought of..If you want to try your hand at creating a regular expression that I need, I’d be more than happy to receive the help!Here are the use-cases:// Should not match''' '' '' '// Should match'one-word''one-word '' one-word'' one-word ''one phrase with whitespace''one phrase with whitespace '' one phrase with whitespace'' one phrase with whitespace '(Then again, I might be overthinking it… ????).Update: Problem solved!Many readers were generous enough to email me their solutions..I want to thank everyone who helped..Thank you so much!The cleanest solution I received is: .*S.* by Daniel O’Connor..This means:.*: Any characterS: Followed one non-whitespace character.*: Followed by any characterOther regexes I received include:.*S+.*by Matt Minks*S.* by Sungbin Jo^s?(?=S)..with a lookahead by KonstantinAnd many others!Here’s a codepen with the updated solution by Daniel.Wrapping upYes, it is possible to validate a form with pure CSS..There are potential problems with validation when whitespace characters are involved.If you don’t mind the whitespaces, it works perfectly..Have fun trying this pattern out!. More details

Leave a Reply