Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

126
Visualizações
Check validity and apply style when user leaves the field

I have an html form somthing like this:

<form id="contactForm">
  <div>
    <label for="name">Name</label>
    <input type="text" name="name" id="name" required minlength="3" />
  </div>
  <button type="submit">Submit</button>
</form>

I am using html validations as my requirements are simple. And I want to display input box in red color if user has entered invalid value. I tried using css pseudo classes valid and invalid like this:

input:invalid {
  background-color: red;
}

The problem with this is that all input fields show up in red even when the user has not touched the field. To prevent this issue I am using on blur event in javascript.

const contactForm = document.forms.contactForm;
const nameInp = contactForm.name;

nameInp.onblur = function () {
  if (this.checkValidity()) {
    console.log("valid");
  } else {
    console.error("invalid");
  }
};

Is it possible to achieve this functionality without javascript using only pseudo classes? I do not want the input boxes to display on red until user clicks on them.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Make use of :placeholder-shown, the input needs to have a placeholder

const contactForm = document.forms.contactForm;
const nameInp = contactForm.name;

nameInp.onblur = function () {
  this.removeAttribute('placeholder');
  if (this.checkValidity()) {
    console.log("valid");
  } else {
    console.error("invalid");
  }
};
input:invalid {
  background-color: red;
}
input:placeholder-shown, input:focus {
  background-color: unset;
}
<form id="contactForm">
  <div>
    <label for="name">Name</label>
    <input type="text" name="name" id="name" required minlength="3" placeholder="name" />
  </div>
  <button type="submit">Submit</button>
</form>

about 4 years ago · Juan Pablo Isaza Relatório

0

No javascript needed!

You can achieve this effect with CSS alone by combining a zero-length placeholder attribute:

  • placeholder=""

with the placeholder-shown pseudo-class:

  • :placeholder-shown

Working Example:

input {
  display: block;
}

input:invalid {
  background-color: red;
}

input:invalid:placeholder-shown {
  background-color: white;
}
<label for="field-1">Field 1:</label>
<input type="text" name="field-1" id="field-1" placeholder="" pattern=".{3,}" required />

<label for="field-2">Field 2:</label>
<input type="text" name="field-2" id="field-2" placeholder="" pattern=".{3,}" required />

<label for="field-3">Field 3:</label>
<input type="text" name="field-3" id="field-3" placeholder="" pattern=".{3,}" required />


Further Reading

  • https://developer.mozilla.org/en-US/docs/Web/CSS/:placeholder-shown
about 4 years ago · Juan Pablo Isaza Relatório

0

OP problem:

The problem with this is that all input fields show up in red even when the user has not touched the field. Is it possible to achieve this functionality without javascript using only pseudo classes? I do not want the input boxes to display on red until user clicks on them.

Add the following after the input:invalid {}

input:not(:focus) {
  background-color: white;
}

input:placeholder-shown {
   background-color: white;
}

Add placeholder= ' ' to each <input>

It's the behavior you described with no JavaScript, just CSS.

input:invalid {
  background-color: red;
}

input:not(:focus) {
  background-color: white;
}

input:placeholder-shown {
  background-color: white;
}
   
<form id="contactForm">
  <fieldset>
    <label>Name</label>
    <input type="text" name="name" placeholder=' ' required minlength="3" /><br>

    <label>Email</label>
    <input type="email" name="email" placeholder=' ' required><br>

    <label>Lucky Number</label>
    <input type="number" name="number" placeholder=' ' required min='0' max='999'>

    <button type="submit">Submit</button>
  </fieldset>
</form>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda