Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

116
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!