First this is not a definitive answer, it does not work in Microsoft browsers ... for a change ...
Now let's get down to business.
What happens here is that input
must have a value of placeholder
, and when it does not have placeholder
it is because the user wrote something inside the input
correct. But how to check if input
is or is not placeholder
? It is there that between this rule of CSS :not(:placeholder-shown)
.
In other words, if it has some value in input
it will not have placeholder
, and if this value is invalid it styles input
with :invalid
. This way input:not(:placeholder-shown):invalid
Now, the input has 3 states and 3 different styles. Blue when :focus
, Red when :invalid
and Green when :valid
input {
width: 100px;
}
input:focus {
border: 2px solid #0050e6;
}
input:required:valid {
border: 2px solid #009900;
}
input:required:not(:placeholder-shown):invalid {
border: 2px solid #c9001b;
}
<input type="email" placeholder="email" required name="" id="">
<input type="email" autofocus placeholder="email" required name="" id="">
<input type="email" value="123" placeholder="email" required name="" id="">
<input type="email" value="[email protected]" placeholder="email" required name="" id="">
<input type="email" placeholder="sem required sem validação" name="" id="">
OBS1: Consult your browser's support for the :placeholder-shown
pseudo-class: link
OBS: 2 The Mozilla documentation on :placeholder-shown
can be seen here: link