Javascript form validation onsubmit not working
<p>I wrote a validation function in Javascript to check that my passwords match. </p>

<p>HTML</p>

<pre><code>&lt;form action="/anotherPage" onsubmit="return validate()" method="POST"&gt;
    &lt;input type="password" name="password"/&gt;
    &lt;input type="password" name="password2"/&gt;

    &lt;button type="submit" class="btn btn-primary"&gt;submit&lt;/button&gt;
&lt;/form&gt;
</code></pre>

<p>Javascript</p>

<pre><code>&lt;script&gt;
  function validate() {
      var ok = true;
      var password = document.getElementById("password").value;
      var password2 = document.getElementById("password2").value;
      if (password != password2) {
          alert("Passwords Do not match");
          document.getElementById("password").style.borderColor = "#E34234";
          document.getElementById("password2").style.borderColor = "#E34234";
          ok = false;
      }
      else {
          alert("Passwords Match!!!");
      }
      return ok;
  }
&lt;/script&gt;
</code></pre>

<p>In console it says form submitted, but I want to validate before form is submitted.But my validation function is never reached. How do I fix this?</p>