前端注册页面密码不一致的代码
时间: 2023-08-24 15:07:21 浏览: 43
在前端注册页面中,当用户输入两次密码不一致时,可以通过 JavaScript 来给出相应的提示信息。以下是一个简单的示例代码:
HTML 代码:
```
<form id="register-form">
<label for="username">用户名:</label>
<input type="text" id="username" name="username">
<label for="password">密码:</label>
<input type="password" id="password" name="password">
<label for="confirm-password">确认密码:</label>
<input type="password" id="confirm-password" name="confirm-password">
<button type="submit">注册</button>
</form>
<div id="error-message" style="color: red; display: none;">两次输入的密码不一致</div>
```
JavaScript 代码:
```
document.querySelector('#register-form').addEventListener('submit', function(event) {
event.preventDefault();
const username = document.querySelector('#username').value;
const password = document.querySelector('#password').value;
const confirmPassword = document.querySelector('#confirm-password').value;
if (!username || !password || !confirmPassword) {
alert('用户名和密码不能为空');
return;
}
if (password !== confirmPassword) {
document.querySelector('#error-message').style.display = 'block';
return;
}
// 发送注册请求
fetch('/api/register', {
method: 'POST',
body: JSON.stringify({ username, password }),
headers: {
'Content-Type': 'application/json'
}
}).then(response => {
if (response.ok) {
alert('注册成功');
} else {
alert('注册失败');
}
});
});
```
在上面的代码中,我们监听了注册表单的提交事件,并获取了用户名、密码和确认密码的值。如果两次输入的密码不一致,就显示相应的错误提示信息,并停止表单的提交。否则,就发送注册请求到后端进行处理。
需要注意的是,上面的代码只是一个简单的示例,实际的注册页面可能会更加复杂,例如需要对密码进行加密等处理。