html+css+js注册页面用正则表达式做
时间: 2023-08-26 19:20:53 浏览: 66
好的,以下是一个简单的注册页面示例,使用 HTML、CSS 和 JavaScript,并使用正则表达式验证输入的邮箱和密码格式。
HTML:
```html
<!DOCTYPE html>
<html>
<head>
<title>注册页面</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
/* 居中显示 */
html, body {
height: 100%;
}
body {
display: flex;
justify-content: center;
align-items: center;
}
/* 表单样式 */
form {
display: flex;
flex-direction: column;
align-items: center;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
}
input[type="text"], input[type="password"] {
margin: 10px;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
width: 300px;
}
input[type="submit"] {
margin: 20px;
padding: 10px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #3e8e41;
}
/* 错误提示信息 */
.error {
color: red;
font-size: 14px;
margin-top: -10px;
}
</style>
</head>
<body>
<form id="register-form">
<label for="email">邮箱:</label>
<input type="text" id="email" name="email" required>
<span class="error" id="email-error"></span>
<label for="password">密码:</label>
<input type="password" id="password" name="password" required>
<span class="error" id="password-error"></span>
<input type="submit" value="注册">
</form>
<script src="index.js"></script>
</body>
</html>
```
CSS:
上面的 HTML 中包含了一些 CSS 样式,用于设置页面布局和表单样式。
JavaScript:
```javascript
// 获取表单元素和错误提示元素
const form = document.getElementById('register-form');
const email = document.getElementById('email');
const emailError = document.getElementById('email-error');
const password = document.getElementById('password');
const passwordError = document.getElementById('password-error');
// 邮箱验证正则表达式
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
// 密码验证正则表达式
const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/;
// 表单提交事件
form.addEventListener('submit', function(event) {
// 阻止默认提交行为
event.preventDefault();
// 验证邮箱格式
if (!emailRegex.test(email.value)) {
emailError.textContent = '请输入有效的邮箱地址';
return;
}
// 清除错误提示
emailError.textContent = '';
// 验证密码格式
if (!passwordRegex.test(password.value)) {
passwordError.textContent = '密码要求至少8个字符,包括至少一个小写字母、一个大写字母和一个数字';
return;
}
// 清除错误提示
passwordError.textContent = '';
// 表单验证通过,可以提交了
alert('注册成功!');
});
```
以上代码实现了一个简单的注册页面,当用户填写邮箱和密码并点击注册按钮时,会使用正则表达式验证邮箱和密码格式。如果格式不正确,则会在对应的输入框下方提示错误信息,阻止表单提交。如果格式正确,则弹出一个注册成功的提示框。
注意:以上代码只是一个示例,实际项目中可能需要更复杂的表单验证逻辑和更完善的错误提示信息。