jebmarcus jebmarcus - 7 months ago 53
HTML Question

Javascript form validation onsubmit not working

I wrote a validation function in Javascript to check that my passwords match.


<form action="/anotherPage" onsubmit="return validate()" method="POST">
<input type="password" name="password"/>
<input type="password" name="password2"/>

<button type="submit" class="btn btn-primary">submit</button>


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;

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?


You are using getElementById - but you don't have input fields with such IDs. Add id="password" and id="password2" to input fields - and magic will happen.