JavaScript实现“表单及时验证”的案例
时间: 2023-09-03 08:10:59 浏览: 139
以下是一个简单的表单及时验证的 JavaScript 实现案例:
HTML 代码:
```
<form>
<label for="name">姓名:</label>
<input type="text" id="name" name="name"><br>
<span id="name-error"></span><br>
<label for="email">邮箱:</label>
<input type="email" id="email" name="email"><br>
<span id="email-error"></span><br>
<label for="password">密码:</label>
<input type="password" id="password" name="password"><br>
<span id="password-error"></span><br>
<button type="submit">提交</button>
</form>
```
JavaScript 代码:
```
// 获取表单元素
const form = document.querySelector('form');
const nameInput = document.getElementById('name');
const emailInput = document.getElementById('email');
const passwordInput = document.getElementById('password');
// 验证姓名
nameInput.addEventListener('input', () => {
const nameError = document.getElementById('name-error');
if (nameInput.value === '') {
nameError.textContent = '姓名不能为空';
} else {
nameError.textContent = '';
}
});
// 验证邮箱
emailInput.addEventListener('input', () => {
const emailError = document.getElementById('email-error');
if (emailInput.value === '') {
emailError.textContent = '邮箱不能为空';
} else if (!emailInput.checkValidity()) {
emailError.textContent = '请输入正确的邮箱格式';
} else {
emailError.textContent = '';
}
});
// 验证密码
passwordInput.addEventListener('input', () => {
const passwordError = document.getElementById('password-error');
if (passwordInput.value === '') {
passwordError.textContent = '密码不能为空';
} else if (passwordInput.value.length < 6) {
passwordError.textContent = '密码长度不能少于6位';
} else {
passwordError.textContent = '';
}
});
// 提交表单
form.addEventListener('submit', (event) => {
event.preventDefault();
// 验证表单是否合法
if (nameInput.value === '') {
document.getElementById('name-error').textContent = '姓名不能为空';
return;
}
if (emailInput.value === '') {
document.getElementById('email-error').textContent = '邮箱不能为空';
return;
} else if (!emailInput.checkValidity()) {
document.getElementById('email-error').textContent = '请输入正确的邮箱格式';
return;
}
if (passwordInput.value === '') {
document.getElementById('password-error').textContent = '密码不能为空';
return;
} else if (passwordInput.value.length < 6) {
document.getElementById('password-error').textContent = '密码长度不能少于6位';
return;
}
// 表单验证通过,提交表单
form.submit();
});
```
以上代码实现了对姓名、邮箱、密码的即时验证,当用户输入不合法时,会在对应的错误提示元素中显示错误信息。当用户点击提交按钮时,会再次验证表单是否合法,若不合法则阻止表单提交并显示错误信息,若合法则提交表单。
阅读全文