繁体   English   中英

密码和密码确认不匹配后如何取消提交表单

[英]How can I cancel submit form after password and password confirmation doesn't match

我正在尝试为我的网站创建一个注册页面,但我不知道如何在密码和确认密码不匹配后阻止用户单击“提交”。

如果两个密码之间不匹配,我有一个“警告”功能。

HTML:

<input type="password" name="password" value="" id="password" placeholder="Password">
<input type="password" name="confirm_password" id="confirm_password" placeholder="Confirm Password" onkeyup='check();'/>
span id='message'></span>

JS:

var check = function() {
  if (document.getElementById('password').value ==
    document.getElementById('confirm_password').value) {
    document.getElementById('message').style.color = 'green';
    document.getElementById('message').innerHTML = 'Passwords are matching';
  } else {
    document.getElementById('message').style.color = 'red';
    document.getElementById('message').innerHTML = 'Passwords does not match' ;
  }
}

我当时在考虑布尔函数,但是我不知道如何在内部调用它以及如何取消提交。

向您的<form onsubmit="validate()">添加验证功能

在submit事件上调用preventDefault将阻止该表单实际提交。

function validate(event) {
  if (!passesValidation) event.preventDefault();
}

您可以在密码不匹配时禁用该按钮

document.getElementById("Button").disabled = false;

在您的JS中,为什么不将值放入变量中? 不必要,但可以使JS更清洁

在该功能Id做类似

var password = document.getElementById('password').value
var confrm_password = document.getElementById('confirm_password').value


const button = document.getElementById('button') (Or however you want to target the button, up to you)

并且比button.disabled = (password === confirm_password))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM