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

119
Visualizações
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 Respostas
Responde à pergunta

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 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