实现前端的用户输入信息准确性校验的代码。
时间: 2024-05-03 22:21:40 浏览: 19
以下代码实现了一个简单的表单校验,包括对手机号、邮箱、密码格式的校验。
HTML:
```html
<form>
<label for="phone">手机号码:</label>
<input type="text" id="phone" name="phone" required>
<label for="email">电子邮箱:</label>
<input type="email" id="email" name="email" required>
<label for="password">密码:</label>
<input type="password" id="password" name="password" required>
<button type="submit">提交</button>
</form>
```
JavaScript:
```javascript
const form = document.querySelector('form');
const phoneInput = document.querySelector('#phone');
const emailInput = document.querySelector('#email');
const passwordInput = document.querySelector('#password');
form.addEventListener('submit', (event) => {
event.preventDefault();
let isValid = true;
// 校验手机号码
const phoneRegex = /^1\d{10}$/;
if (!phoneRegex.test(phoneInput.value)) {
phoneInput.setCustomValidity('请输入有效的手机号码');
isValid = false;
} else {
phoneInput.setCustomValidity('');
}
// 校验电子邮箱
const emailRegex = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
if (!emailRegex.test(emailInput.value)) {
emailInput.setCustomValidity('请输入有效的电子邮箱');
isValid = false;
} else {
emailInput.setCustomValidity('');
}
// 校验密码
const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[\s\S]{8,}$/;
if (!passwordRegex.test(passwordInput.value)) {
passwordInput.setCustomValidity('密码必须包含大小写字母和数字,且长度不少于8位');
isValid = false;
} else {
passwordInput.setCustomValidity('');
}
// 提交表单
if (isValid) {
form.submit();
}
});
```
在上面的代码中,我们使用HTML5表单的`required`属性来确保用户必须输入所有字段。然后,在表单提交时,我们使用JavaScript来对每个字段进行校验。如果校验失败,我们使用`setCustomValidity`方法来设置错误信息,并将`isValid`变量设置为`false`。最后,如果所有字段都通过了校验,我们就提交表单。
相关推荐
![](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)
![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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)