用户注册网站密码的安全性非常重要,所以,我们在制作用户注册页面时,一般会提示用户输入两次密码,然后,比较用户两次输入的密码是否一致,那么,问题来了我们该如何验证用户两次输入的内容是否一致呢?接下来,济南网站建设小编就为大家介绍,通过编写JavaScript编码来设置验证用户两次输入密码是否一致的小方法,有需要的朋友可以过来参考一下。
关键代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title>JavaScript验证两次密码一致性校验</title>
<style>
.box {
width: 350px;
margin: 50px auto;
}
.item {
margin: 15px 0;
}
input {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 14px;
}
.tip {
font-size: 13px;
margin-top: 5px;
}
.success {
color: green;
}
.error {
color: red;
}
</style>
</head>
<body>
<div class="box">
<div class="item">
<input type="password" id="pwd" placeholder="请输入密码">
</div>
<div class="item">
<input type="password" id="repwd" placeholder="请再次输入密码">
<div class="tip" id="msg"></div>
</div>
</div>
<script>
// 获取元素
const pwd = document.getElementById('pwd');
const repwd = document.getElementById('repwd');
const msg = document.getElementById('msg');
// 监听第二个密码框输入事件
repwd.oninput = function () {
let pwdVal = pwd.value;
let repwdVal = repwd.value;
// 先清空提示
msg.innerText = '';
// 非空时开始比对
if (repwdVal === '') {
return;
}
if (pwdVal === repwdVal) {
msg.className = 'tip success';
msg.innerText = '两次密码输入一致';
} else {
msg.className = 'tip error';
msg.innerText = '两次密码输入不一致,请重新核对';
}
}
</script>
</body>
</html>
评论