常见的前端输入验证方法
前端输入验证是确保用户输入数据符合预期格式和规则的关键步骤,能够有效防止恶意数据提交和提升用户体验。常见的验证方法包括基础验证、正则表达式验证、自定义函数验证以及利用现成库或框架提供的验证机制。
基础HTML5表单验证
HTML5内置了多种输入类型和属性,可直接用于基础验证。例如:
<input type="email" required placeholder="请输入邮箱">
<input type="password" minlength="8" required>
<input type="number" min="18" max="100">
这些类型和属性包括:
required
:字段必填type="email"
:验证邮箱格式type="url"
:验证URL格式min/max
:数值范围限制pattern
:使用正则表达式验证
正则表达式验证
正则表达式能处理更复杂的验证场景。以下是常见用例:
// 验证手机号(中国大陆)
function validatePhone(phone) {
return /^1[3-9]\d{9}$/.test(phone);
}
// 验证身份证号(简易版)
function validateIDCard(id) {
return /^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/.test(id);
}
// 验证密码强度(至少包含大小写字母和数字)
function validatePassword(pwd) {
return /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,}$/.test(pwd);
}
自定义JavaScript验证函数
对于业务特定的验证逻辑,需要编写自定义函数:
function validateForm() {
const username = document.getElementById('username').value;
if (username.length < 4 || username.length > 16) {
showError('用户名长度需在4-16字符之间');
return false;
}
const age = parseInt(document.getElementById('age').value);
if (isNaN(age) || age < 0 || age > 150) {
showError('请输入有效的年龄');
return false;
}
return true;
}
function showError(message) {
const errorEl = document.createElement('div');
errorEl.className = 'error-message';
errorEl.textContent = message;
document.querySelector('form').prepend(errorEl);
}
实时输入验证
通过事件监听实现输入时即时反馈:
document.getElementById('email').addEventListener('input', (e) => {
const email = e.target.value;
const isValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
e.target.classList.toggle('invalid', !isValid);
});
// CSS配合
.invalid {
border-color: red;
}
第三方验证库
常用验证库提供更全面的解决方案:
- Validator.js:
import validator from 'validator';
validator.isEmail('foo@bar.com'); // true
validator.isMobilePhone('13800138000', 'zh-CN'); // true
- Yup(常用于表单库如Formik):
const schema = yup.object().shape({
name: yup.string().required().min(2),
email: yup.string().email().required(),
age: yup.number().positive().integer()
});
文件上传验证
文件类型和大小验证尤为重要:
const fileInput = document.getElementById('avatar');
fileInput.addEventListener('change', (e) => {
const file = e.target.files[0];
const validTypes = ['image/jpeg', 'image/png'];
const maxSize = 2 * 1024 * 1024; // 2MB
if (!validTypes.includes(file.type)) {
alert('仅支持JPEG/PNG格式');
e.target.value = '';
}
if (file.size > maxSize) {
alert('文件大小不能超过2MB');
e.target.value = '';
}
});
防御性编程技巧
- 双重验证:前端验证后,服务端必须再次验证
- 白名单原则:只允许已知安全的输入模式
- 转义输出:即使通过验证,显示时仍需转义
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
验证反馈的最佳实践
- 明确提示错误原因
- 错误定位到具体字段
- 避免使用技术术语
- 提供纠正建议
<div class="field">
<label for="password">密码</label>
<input type="password" id="password" aria-describedby="password-help">
<div id="password-help" class="hint">
至少8个字符,包含大小写字母和数字
</div>
<div id="password-error" class="error" hidden>
<svg>...</svg>
<span>密码不符合要求</span>
</div>
</div>
防止自动化提交
增加人机验证措施:
// 简单的防抖验证
let submitCount = 0;
document.querySelector('form').addEventListener('submit', (e) => {
if (submitCount > 2) {
e.preventDefault();
showCaptcha();
}
submitCount++;
});
// Google reCAPTCHA集成示例
function onSubmit(token) {
document.getElementById("demo-form").submit();
}
现代浏览器API验证
利用Constraint Validation API增强原生验证:
const emailInput = document.getElementById('email');
if (!emailInput.checkValidity()) {
console.log(emailInput.validationMessage);
// 例如:"请包含'@'符号"
}
// 自定义错误消息
emailInput.addEventListener('invalid', () => {
if (emailInput.value === '') {
emailInput.setCustomValidity('请输入邮箱地址');
} else {
emailInput.setCustomValidity('邮箱格式不正确,应包含@和域名');
}
});
emailInput.addEventListener('input', () => {
emailInput.setCustomValidity('');
});
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益,请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:客户端验证 vs 服务端验证
下一篇:防止 SQL 注入的前端措施