Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

127
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda