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

118
Vistas
Can't get form to validate

I have to make a form that has a username and password but the password must be five or more characters. I have tried a lot of different methods but none have succeded.

Here's my javascript:

funtion validateForm(){
var password = document.getElementById('password').value;
if (password.length < 5)
  alert("Password must be longer");
  return false;
}
}

and my HTML:

<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title>Login</title>
        <script src="js/script.js" charset="utf-8"></script>
    </head>
    <body>
        <div id="error">

        </div>
        <form name="formname" action="/action_page.php" onsubmit="validateForm()" method="post">
<div>
    <label for="name">Username:</label>
    <input id="username" name="name" type="text" required>
</div>
<div>
    <label for="password">Password:</label>
    <input id="password" name="password" type="password">
<input type="submit" value="Submit">
</div>
    </form>
    </body>
</html>



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

0

You need to use Event.preventDefault() to prevent the form submit on validation fail. And to do that you need to pass the event to your handler like onsubmit="validateForm(event)".

See the code snippet to understand how it works.

function validateForm(event) {

  var password = document.getElementById('password').value;
 
  if (password.length < 5) {
    event.preventDefault();    // <--- ADDED
    alert("Password must be longer");
    return false;
  }
  
}
<div id="error">

</div>
<form name="formname" action="/action_page.php" onsubmit="validateForm(event)" method="post">
  <div>
    <label for="name">Username:</label>
    <input id="username" name="name" type="text" required>
  </div>
  <div>
    <label for="password">Password:</label>
    <input id="password" name="password" type="password">
    <input type="submit" value="Submit">
  </div>
</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