CSS: Validação visual input text

Criando um campo com validação utilizando css puro.

Nosso objetivo é que:

  • Quando o campo estiver vazio o label atue como placeholder.
  • Quando o campo estiver com foco o fundo fique cinza.
  • Quando o campo for válido o fundo fique verde.
  • Quando o campo for inválido o fundo fique vermelho.

Css:


.custom-input {
    background: white;
    border: 1px solid lightgray;
    border-radius:5px;
    height:50px;
    position: relative;
}

.valid {
    background: lightgreen;
}

.invalid {
    background: #ffb3b3;
}

.custom-input:focus-within {
    background: lightgray;
}

.custom-input :placeholder-shown ~ label {
    display: block;
    background: inherit;
    font-size: 20px;
    padding-top: 10px;
    padding-left: 10px;
    top:0;
    position:absolute;
}

.custom-input input {
    background: inherit;
    width:100%;
    border: none;
    height: 18px;
    position: absolute;
    bottom:0;
}
.custom-input input:not(:placeholder-shown) ~ label, .custom-input input:focus ~ label {
    font-size: 12px;
    padding: 5px;
    font-weight: bold;
}

Html:


<div class="custom-input">
<input type="email" id="exampleFormControlInput1" placeholder=" ">
<label for="exampleFormControlInput1" >Email address</label>
</div>
<br>
<div class="custom-input valid">
<input type="email" id="exampleFormControlInput1" placeholder=" ">
<label for="exampleFormControlInput1" >Email address</label>
</div>
<br>
<div class="custom-input invalid">
<input type="email" id="exampleFormControlInput1" placeholder=" ">
<label for="exampleFormControlInput1" >Email address</label>
</div>

Resultado: 

Screenshot from 2020-01-09 16-20-34

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this:
search previous next tag category expand menu location phone mail time cart zoom edit close