在日常ref="/tag/190/" style="color:#C468A7;font-weight:bold;">办公中,很多公司都会用到内部系统提交数据,比如请假申请、报销填写或者客户信息登记。如果用户填错了手机号、邮箱格式不对,或者漏填必填项,直接提交到服务器不仅浪费时间,还可能影响后续流程。这时候,用JavaScript代码验证表单就显得特别实用。
为什么要在前端做表单验证
很多人觉得“后台会检查,前端不用管”,但其实前端验证能立刻给用户反馈。比如销售小李填客户邮箱时手滑打成 gmail.con,页面马上提示“邮箱格式不正确”,他就能立刻改过来,而不是等几秒后弹出错误,再回头找哪里错了。
一个简单的必填字段验证示例
比如要确保用户名不能为空,可以这样写JavaScript代码:
function validateForm() {
let name = document.getElementById("username").value;
if (name === "") {
alert("用户名不能为空");
return false;
}
return true;
}
把这个函数绑定到表单的提交事件上,就能在提交前拦截空值。
验证邮箱格式的小技巧
邮箱不能只看是否为空,还得判断格式。虽然正则表达式看起来有点吓人,但拿来即用很方便:
function validateEmail() {
let email = document.getElementById("email").value;
let regex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;
if (!regex.test(email)) {
alert("请输入有效的邮箱地址");
return false;
}
return true;
}
测试时输入 test@company、admin@ 这类明显错误的格式,都会被拦下来。
手机号验证也很常见
国内手机号通常是11位数字,以1开头。可以用长度和正则一起判断:
function validatePhone() {
let phone = document.getElementById("phone").value;
if (!/^1[0-9]{10}$/.test(phone)) {
alert("请输入正确的手机号码");
return false;
}
return true;
}
财务部门做报销系统时加上这个,能避免员工填错联系方式导致打款失败。
结合HTML结构一起用
完整的表单可以这样组织:
<form onsubmit="return validateForm() && validateEmail() && validatePhone()">
<input type="text" id="username" placeholder="用户名">
<input type="email" id="email" placeholder="邮箱">
<input type="tel" id="phone" placeholder="手机号">
<button type="submit">提交</button>
</form>
每个验证函数返回true才允许提交,逻辑清晰又实用。
提升体验:不用alert也能提示
频繁弹alert太生硬,可以改成在页面上显示提示文字:
function validateEmail() {
let email = document.getElementById("email").value;
let error = document.getElementById("email-error");
let regex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;
if (!regex.test(email)) {
error.textContent = "邮箱格式不对,请检查";
return false;
} else {
error.textContent = "";
return true;
}
}
对应加一行提示标签:<span id="email-error" style="color:red;"></span>,界面更友好。
这类验证在行政、人事、客服系统的网页中特别常见,花几十行JavaScript就能省下不少沟通成本。