我在Javascript中編寫了一個驗證函數來檢查我的密碼是否匹配。Javascript表單驗證onsubmit不工作
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>
在控制檯,它說的形式提交,但我想驗證形式submitted.But永遠達不到我的驗證功能之前。我該如何解決?
控制檯中的錯誤? – mplungjan
在控制檯中它表示提交表單,但我想在表單提交之前進行驗證。驗證功能從未達到。 –
在你的html中你寫了''並且在你的js'document.getElementById(「password」)'中。您應該爲兩個密碼元素添加id屬性。 –