js实现有验证功能的登陆表单
时间: 2024-06-09 16:06:23 浏览: 6
以下是一个简单的JavaScript登陆表单验证代码示例:
HTML代码:
```html
<form id="login-form">
<label for="username">用户名:</label>
<input type="text" id="username" name="username" required><br>
<label for="password">密码:</label>
<input type="password" id="password" name="password" required><br>
<input type="submit" value="登陆">
</form>
```
JavaScript代码:
```javascript
// 获取表单元素
const form = document.getElementById("login-form");
const usernameInput = document.getElementById("username");
const passwordInput = document.getElementById("password");
// 提交表单时验证
form.addEventListener("submit", function(event) {
// 阻止默认提交行为
event.preventDefault();
// 验证输入的用户名和密码
const username = usernameInput.value.trim();
const password = passwordInput.value.trim();
if (username === "" || password === "") {
alert("用户名和密码不能为空!");
return;
}
// 发送登陆请求
// ...
// 清空表单
form.reset();
});
```
上述代码中,我们通过`document.getElementById`方法获取了表单及其内部的用户名和密码输入框,然后通过`addEventListener`方法监听了表单的提交事件。在事件处理函数中,我们首先阻止了默认的表单提交行为,然后获取了输入的用户名和密码,并对其进行了非空验证。如果用户名或密码为空,则弹出一个提示框,并返回。否则,我们可以继续发送登陆请求(这里没有写出具体的请求代码),并在最后清空表单内容以便下一次使用。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)