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

185
Vistas
Error message displayed even with valid inputs

I was trying to validate my HTML form with the help of Javascript, but the error messages get displayed even after providing valid inputs. If I add 'preventDefault()', the error messages get displayed only with invalid inputs but the form gets submitted anyway. My code-

HTML

<form id="form" novalidate onsubmit="return validate()">

<label for="firstName">Enter your first name</label><br>
<input type="text" id="firstName" name="firstName" required><br>
<span role="alert" id="nameError" aria-hidden="true"> Please enter a valid name </span>
<label for="lastName">Enter your last name here</label><br>
<input type="text" id="lastName" name="lastName" required><br>
<span role="alert" id="lastNameError" aria-hidden="true"> Please enter a valid name </span> 
/*other elements in the form */

Javascript for error messages

const firstNameField = document.getElementById("firstName");
const lastNameField = document.getElementById("lastName");

let valid = true;

if (firstNameField.getAttribute(length)<3
|| firstNameField.getAttribute(pattern)!="[A-Za-z+]"
|| lastNameField.getAttribute(length)<3
|| lastNameField.getAttribute(pattern)!="[A-Za-z+]")
 {
const nameError = document.getElementById("nameError");
nameError.classList.add("visible");
firstNameField.classList.add("invalid");
nameError.setAttribute('aria-hidden', false);
nameError.setAttribute('aria-invalid', true);

const lastNameError = document.getElementById("lastNameError");
lastNameError.classList.add("visible");
lastNameField.classList.add("invalid");
lastNameError.setAttribute('aria-hidden', false);
lastNameError.setAttribute('aria-invalid', true);


valid = false;

}

return valid;
}

CSS for the error messages

#nameError, #lastNameError{
display: none;
font-size: 0.8em;
color: red;
}

#nameError.visible, #lastNameError.visible{
  display: block;
}

input.invalid {
 border-color: red;
}

I'm new to Javascript so any suggestions would be helpful for me

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

In addition to preventDefault() also add, stopPropagation() to prevent the submit event from bubbling up to the form and submitting it.

about 4 years ago · Juan Pablo Isaza Denunciar

0

It seems like you are missing the closing bracket on your if condition.

Also try to make a runnable example with snippet this description on stackoverflow should help

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can do something like this in js:

document.getElementById('form').addEventListener('submit', function(e) {  
  e.preventDefault();
  console.log('run validation here, return true or false to submit');
}
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