Member-only story
I Don’t Think We Really Need :user-valid or :user-invalid
Psst! Click here to read it for free!
There’s been a lot of buzz in the web dev sphere lately about :user-valid
and :user-invalid
. For those who don’t know them, they are an alternative to the pseudo-selectors :valid
and :invalid
that can be used to style input fields, like so:
/*old way*/
input:valid { border: green 1px solid; }
input:invalid { border: red 1px solid; }
The problem here is that if an input is set to be required, it’s styled as invalid by default. Alternatively, if it’s not set to be required, it’s styled as valid by default. This means invalid inputs get a red border on-load, while valid inputs get a green border on-load.
:user-valid
and :user-invalid
get around that by waiting for the user to interact with the input first. Only after the user interacts with a required field, does it style it as invalid or valid.
/*new way*/
input:user-valid { border: green 1px solid; }
input:user-invalid { border: red 1px solid; }
This is great… but we already had a selector that can do this this: :placeholder-shown
input:valid:not(:placeholder-shown) { border: green 1px solid; }
input:invalid:placeholder-shown { border: red 1px solid; }