我无法阻止提交此表单(如果验证失败)。
该表单具有 onSubmit="return validateThisFrom (this);"
属性。
<form action="php/create-user.php" method="POST" onSubmit="return validateThisFrom (this);">
如果密码不匹配,validate 函数应该返回 false。这些是密码字段及其 ID。
<input type="password" id="password">
<input type="password" id="confirm_password">
这是功能
function validateThisFrom(thisForm) {
var pwd1 = document.getElementById('password').value;
var pwd2 = document.getElementById('confirm_password').value;
if (thisForm.password.value != thisForm.confirm_password.value) {
document.getElementById('message').style.color = '#dc3545';
document.getElementById('message').style.fontSize = '13px';
document.getElementById('message').innerHTML = '<b>The passwords don\'t match!</b>.';
document.getElementById('password').style.borderColor = '#dc3545';
document.getElementById('confirm_password').style.borderColor = '#dc3545';
document.getElementById('button-addon1').style.borderColor = '#dc3545';
document.getElementById('button-addon2').style.borderColor = '#dc3545';
return false;
}
}
出现 The password don't Match
消息,但随后即使函数返回 false,表单仍被提交。
正如您在照片中看到的那样,消息出现,但随后正在提交表单。
答案 0 :(得分:1)
我在自己的 PC 上检查了您的代码,您的 if 中的元素之一似乎有问题。当我删除所有这些 document.getElementById... 并执行程序时,它会工作得很好。检查所有这些元素并确保它们都存在于您的 html 文件中,并且您已正确写入了它们的 id。当我将它们添加到我的代码中时问题解决了。