编写登录页面,页面中有userID和password,前端校验是userID不能出现字母,密码必须6位;校验通过
时间: 2024-02-28 10:57:02 浏览: 27
下面是一个简单的登录页面的示例代码,包括了前端校验逻辑:
```html
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<style>
form {
display: flex;
flex-direction: column;
align-items: center;
margin-top: 50px;
}
input {
margin-bottom: 10px;
}
button {
margin-top: 10px;
}
.error {
color: red;
margin-bottom: 10px;
}
</style>
</head>
<body>
<form>
<label for="userID">User ID:</label>
<input type="text" id="userID" name="userID">
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<button type="submit">Login</button>
<p class="error" id="error"></p>
</form>
<script>
const form = document.querySelector('form');
const userIDInput = document.querySelector('#userID');
const passwordInput = document.querySelector('#password');
const errorText = document.querySelector('#error');
form.addEventListener('submit', e => {
e.preventDefault();
const userID = userIDInput.value.trim();
const password = passwordInput.value.trim();
if (/^[0-9]+$/.test(userID) && password.length === 6) {
// validation passed
alert('Validation passed!');
form.submit();
} else {
// validation failed
errorText.textContent = 'User ID must be all numbers, password must be 6 characters long.';
}
});
</script>
</body>
</html>
```
解释:
- HTML 部分包含了登录表单、错误提示信息的标签。
- CSS 部分设置了表单元素的样式,以及错误提示信息的样式。
- JavaScript 部分通过使用 `querySelector` 方法获取表单元素和错误提示信息的引用,然后监听表单的提交事件,进行前端校验。
- 前端校验逻辑:当用户填写的 User ID 只包含数字且 Password 的长度为 6 时,校验通过,否则提示错误信息。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)