jebmarcus jebmarcus - 3 months ago 22
HTML Question

Javascript form validation onsubmit not working

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

HTML

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


Javascript

<script>
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;
}
</script>


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?

Answer

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.

Comments