好看的前端登录界面并结合正则表达式
时间: 2023-07-25 22:07:45 浏览: 77
以下是一个简单的前端登录界面,并使用正则表达式对输入进行验证:
```html
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<style>
body {
background-color: #f0f0f0;
font-family: Arial, sans-serif;
}
.container {
margin: 50px auto;
width: 400px;
background-color: #fff;
padding: 20px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0,0,0,0.2);
}
h1 {
text-align: center;
}
label {
display: block;
margin-bottom: 10px;
}
input[type="text"], input[type="password"] {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
margin-bottom: 20px;
font-size: 16px;
}
input[type="submit"] {
background-color: #008CBA;
color: #fff;
border: none;
padding: 10px;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #00698F;
}
.error {
color: red;
font-size: 14px;
margin-top: 5px;
}
</style>
</head>
<body>
<div class="container">
<h1>Login</h1>
<form action="">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<input type="submit" value="Login">
<div class="error" id="username-error"></div>
<div class="error" id="password-error"></div>
</form>
</div>
<script>
// 验证用户名和密码是否符合要求
function validate() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var usernameRegex = /^[a-zA-Z0-9]{6,20}$/; // 只允许字母和数字,长度为6到20
var passwordRegex = /^[a-zA-Z0-9!@#$%^&*()_+-=]{8,20}$/; // 只允许字母、数字和特殊字符,长度为8到20
var usernameError = document.getElementById("username-error");
var passwordError = document.getElementById("password-error");
if (!usernameRegex.test(username)) {
usernameError.innerHTML = "Username should be 6-20 characters long and only contain letters and numbers.";
return false;
} else {
usernameError.innerHTML = "";
}
if (!passwordRegex.test(password)) {
passwordError.innerHTML = "Password should be 8-20 characters long and only contain letters, numbers and special characters.";
return false;
} else {
passwordError.innerHTML = "";
}
return true;
}
// 表单提交时验证
document.querySelector("form").addEventListener("submit", function(event) {
if (!validate()) {
event.preventDefault();
}
});
</script>
</body>
</html>
```
在这个例子中,我们使用了正则表达式来限制用户名和密码的输入格式。在 `validate` 函数中,我们使用 `test` 方法对输入进行验证,并在必要时显示错误消息。在表单提交时,我们调用 `validate` 函数来确保输入格式正确。
阅读全文