How to prevent an Input Required from starting with the CSS style: invalid

7

When I have a input required that has some CSS style when it is :invalid , even before the user interacts with input it already becomes stylized as invalid. How can I avoid this?

See the example:

input:invalid {
  border: 2px solid red;
}
input:valid {
  border: 2px solid green;
}
input {
  border: 2px solid blue;
}
Esse input já começa estilizado com inválido, mesmo sem o usuário ter interagido com ele: <br>
<input type="email" required placeholder="email">

But I would like it to only be styled as :invalid after it is populated and invalidated by patter, or another HTML attribute, not before the user clicks on it or anything.

I would like an option with CSS only

If the field is populated with invalid values, it should remain stylized as invalid even after the user takes focus from the field     
asked by anonymous 05.09.2018 / 21:13

1 answer

3

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

    
05.09.2018 / 23:27