38. JS表单验证(附带示例)
1. 前言
表单是 Web 应用(网站)的重要组成部分,通过表单可以收集用户提交的信息,例如姓名、邮箱、电话等。由于用户在填写这些信息时,有可能出现一些错误,例如输入手机号时漏掉了一位、在输入的内容前后输入空格、邮箱的格式不正确等。为了节省带宽同时避免这些问题对服务器造成不必要的压力,我们可以使用 JavaScript 在提交数据之前对数据进行检查,确认无误后再发送到服务器。
使用 JavaScript 来验证提交数据(客户端验证)比将数据提交到服务器再进行验证(服务器端验证)用户体验要更好,因为客户端验证发生在用户浏览器中,无需向服务器发送请求,所以速度更快,而服务器端验证,需要先将数据提交到服务器,然后服务器再将结果返回给浏览器,用户需要等待服务器响应结果才能知道哪里出了问题。
注意:虽然客户端验证更快,但是客户端验证并不能替代服务器端验证。在开发过程中,无论是否进行客户端验证,都需要在服务器端对于用户提交的数据进行验证,因为用户可以在浏览器中禁用 JavaScript。
2. 使用 JavaScript 进行表单验证
表单验证通常由两个部分组成:
- 必填字段验证:确保必填的字段都被填写;
- 数据格式验证:确保所填内容的类型和格式是正确的、有效的。
3. 必填字段验证
必填字段验证在用户注册时比较常见,通过必填字段验证,能够确保表单中的必填字段都被填写,例如用户名、密码、邮箱等。
实现必填字段验证非常简单,只需要通过程序来检查必填表单元素的值是否为空即可,示例代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 | <!DOCTYPE html> <html lang= "en" > <head> <meta charset= "UTF-8" > <title>JavaScript</title> <style> .error{ color: red; } label{ display: inline-block; width: 70px; text-align: right; } </style> </head> <body> <form onsubmit= "return validateForm()" action= "" method= "post" > <fieldset> <legend>注册:</legend> <div class = "row" > <label>用户名:</label> <input type= "text" name= "name" > <span class = "error" id= "nameErr" ></span> </div> <div class = "row" > <label>密码:</label> <input type= "password" name= "pwd" > <span class = "error" id= "pwdErr" ></span> </div> <div class = "row" > <label>Email:</label> <input type= "text" name= "email" > <span class = "error" id= "emailErr" ></span> </div> <div class = "row" > <label>手机号:</label> <input type= "text" name= "mobile" maxlength= "11" > <span class = "error" id= "mobileErr" ></span> </div> <div class = "row" > <label>验证码:</label> <input type= "text" name= "captcha" maxlength= "4" ><span id= "captcha" onclick= "getCaptcha()" ></span> <span class = "error" id= "captchaErr" ></span> </div> <div class = "row" > <input type= "submit" value= "注册" > </div> </fieldset> </form> <script> var captcha = getCaptcha(); // 生成验证码 // 清空 input 标签后的提示信息 var tags = document.getElementsByTagName( 'input' ); for ( var i = 0; i < tags.length; i++) { tags[i].onchange = function(){ var idname = this .name + "Err" ; document.getElementById(idname).innerHTML = '' ; } } // 显示错误消息 function printError(elemId, hintMsg) { document.getElementById(elemId).innerHTML = hintMsg; } // 验证表单数据 function validateForm() { // 获取表单元素的值 var name = document.querySelector( "input[name='name']" ).value; var pwd = document.querySelector( "input[name='pwd']" ).value; var email = document.querySelector( "input[name='email']" ).value; var mobile = document.querySelector( "input[name='mobile']" ).value; var captcha = document.querySelector( "input[name='captcha']" ).value; if (name == "" || name == null ){ printError( "nameErr" , "用户名不能为空" ); return false ; } if (pwd == "" || pwd == null ){ printError( "pwdErr" , "密码不能为空" ); return false ; } if (email == "" || email == null ){ printError( "emailErr" , "邮箱不能为空" ); return false ; } if (mobile == "" || mobile == null ){ printError( "mobileErr" , "手机号不能为空" ); return false ; } if (captcha == "" || captcha == null ){ printError( "captchaErr" , "验证码不能为空" ); return false ; } } // 获取验证码 function getCaptcha(){ var cap = Math.floor(Math.random()*10000).toString(); if (cap.length != 4) cap += "0" ; captcha = cap; document.getElementById( "captcha" ).innerHTML = cap; } </script> </body> </html> |
运行结果如下:

图:必填字段验证
4. 数据格式验证
数据格式验证就是通过正则表达式来验证用户所填的数据,是否符合要求,以邮箱地址为例,正确的邮箱地址中要包含一个@
和一个.
,而且@
不能是邮箱地址的第一个字符,.
要出现在@
之后。
示例代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 | <!DOCTYPE html> <html lang= "en" > <head> <meta charset= "UTF-8" > <title>JavaScript</title> <style> .error{ color: red; } label{ display: inline-block; width: 70px; text-align: right; } </style> </head> <body> <form onsubmit= "return validateForm()" action= "" method= "post" > <fieldset> <legend>注册:</legend> <div class = "row" > <label>用户名:</label> <input type= "text" name= "name" > <span class = "error" id= "nameErr" ></span> </div> <div class = "row" > <label>密码:</label> <input type= "password" name= "pwd" > <span class = "error" id= "pwdErr" ></span> </div> <div class = "row" > <label>Email:</label> <input type= "text" name= "email" > <span class = "error" id= "emailErr" ></span> </div> <div class = "row" > <label>手机号:</label> <input type= "text" name= "mobile" maxlength= "11" > <span class = "error" id= "mobileErr" ></span> </div> <div class = "row" > <label>验证码:</label> <input type= "text" name= "captcha" maxlength= "4" ><span id= "captcha" onclick= "getCaptcha()" ></span> <span class = "error" id= "captchaErr" ></span> </div> <div class = "row" > <input type= "submit" value= "注册" > </div> </fieldset> </form> <script> var capCode = getCaptcha(); // 生成验证码 console.log(capCode); // 清空 input 标签后的提示信息 var tags = document.getElementsByTagName( 'input' ); for ( var i = 0; i < tags.length; i++) { tags[i].onchange = function(){ var idname = this .name + "Err" ; document.getElementById(idname).innerHTML = '' ; } } // 显示错误消息 function printError(elemId, hintMsg) { document.getElementById(elemId).innerHTML = hintMsg; } // 验证表单数据 function validateForm() { // 获取表单元素的值 var name = document.querySelector( "input[name='name']" ).value; var pwd = document.querySelector( "input[name='pwd']" ).value; var email = document.querySelector( "input[name='email']" ).value; var mobile = document.querySelector( "input[name='mobile']" ).value; var captcha = document.querySelector( "input[name='captcha']" ).value; if (name == "" || name == null ){ printError( "nameErr" , "用户名不能为空" ); return false ; } if (pwd == "" || pwd == null ){ printError( "pwdErr" , "密码不能为空" ); return false ; } if (email == "" || email == null ){ printError( "emailErr" , "邮箱不能为空" ); return false ; } else { var regex = /^\S+@\S+\.\S+$/; if (regex.test(email) === false ) { printError( "emailErr" , "请输入正确的邮箱地址" ); return false ; } } if (mobile == "" || mobile == null ){ printError( "mobileErr" , "手机号不能为空" ); return false ; } else { var regex = /^[1]\d{10}$/; if (regex.test(mobile) === false ) { printError( "mobileErr" , "您输入的手机号码有误" ); return false ; } } if (captcha == "" || captcha == null ){ printError( "captchaErr" , "验证码不能为空" ); return false ; } else { console.log(capCode); console.log(captcha); if (capCode != captcha){ printError( "captchaErr" , "验证码有误" ); return false ; } } } // 获取验证码 function getCaptcha(){ var cap = Math.floor(Math.random()*10000).toString(); if (cap.length != 4) cap += "0" ; document.getElementById( "captcha" ).innerHTML = cap; return capCode = cap; } </script> </body> </html> |
运行结果如下:

图:数据格式验证
分类:
JavaScript
标签:
JavaScript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现