js实现表单验证提交表单提交表单
表单验证的基本实现
表单验证可以通过JavaScript监听表单的提交事件,阻止默认提交行为,检查输入字段的有效性。若验证通过,手动提交表单;若验证失败,显示错误信息。
document.getElementById('myForm').addEventListener('submit', function(event) {
event.preventDefault();
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
if (!email.includes('@')) {
alert('请输入有效的邮箱地址');
return;
}
if (password.length < 6) {
alert('密码长度不能少于6位');
return;
}
this.submit();
});
实时输入验证
在用户输入时实时验证字段,提供即时反馈。可以为每个输入字段添加input或blur事件监听器。
document.getElementById('email').addEventListener('blur', function() {
const emailError = document.getElementById('emailError');
if (!this.value.includes('@')) {
emailError.textContent = '请输入有效的邮箱地址';
} else {
emailError.textContent = '';
}
});
使用HTML5内置验证
结合HTML5的表单验证属性,如required、pattern、minlength等,减少JavaScript代码量。

<input type="email" id="email" required>
<input type="password" id="password" minlength="6" required>
显示自定义错误信息
通过setCustomValidity方法设置自定义验证消息,覆盖浏览器默认的提示。
document.getElementById('password').addEventListener('input', function() {
if (this.value.length < 6) {
this.setCustomValidity('密码长度不能少于6位');
} else {
this.setCustomValidity('');
}
});
异步验证
对于需要与服务器交互的验证(如用户名是否已存在),可以使用fetch进行异步验证。

document.getElementById('username').addEventListener('blur', function() {
fetch('/check-username?username=' + this.value)
.then(response => response.json())
.then(data => {
if (data.exists) {
document.getElementById('usernameError').textContent = '用户名已存在';
}
});
});
验证库的使用
对于复杂表单,可以使用现成的验证库如Validator.js或Yup,简化验证逻辑。
import * as yup from 'yup';
const schema = yup.object().shape({
email: yup.string().email().required(),
password: yup.string().min(6).required()
});
schema.validate(formData)
.then(() => form.submit())
.catch(err => alert(err.errors[0]));
防止多次提交
在表单提交时禁用提交按钮,防止用户多次点击导致重复提交。
document.getElementById('myForm').addEventListener('submit', function() {
const submitBtn = document.getElementById('submitBtn');
submitBtn.disabled = true;
});
验证全部通过后提交
收集所有字段的验证状态,只有全部通过时才允许提交表单。
function validateForm() {
const isEmailValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.value);
const isPasswordValid = password.value.length >= 6;
return isEmailValid && isPasswordValid;
}
form.addEventListener('submit', function(e) {
if (!validateForm()) {
e.preventDefault();
alert('请正确填写所有字段');
}
});






