原生js验证表单
html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>表单</title> <link rel="shortcut icon" type="image/x-icon" href="../img/ic.png"/> <link rel="stylesheet" href="../css/form.css"/> <script src="../js/vailidate.js"></script> </head> <body> <h1>用户注册</h1> <form action="demo1.html" method="post" enctype="multipart/form-data" class="register"> <!-- 用户名 --> <div> <label for="userName">用户名</label> <input placeholder="输入用户名" type="text" name="userName" class="userName" id="userName"/> <span>*</span> </div> <input type="hidden" name="id" value="1"/> <!-- 密码 --> <div> <label for="password">密码</label> <input type="password" name="password" id="password" class="password" placeholder="输入密码"/> <span>*</span> </div> <div> <label for="realName">真实姓名</label> <input placeholder="输入用户名" type="text" name="realName" class="realName" id="realName"/> <span>*</span> </div> <!-- 性别单选框 --> <div> <label>性别</label> <input type="radio" name="gender" value="男" checked/>男 <input type="radio" name="gender" value="女"/>女 <span> </span> </div> <!-- 爱好复选框 --> <div> <label>爱好</label> <input type="checkbox" name="hobby" value="LOL"/>LOL <input type="checkbox" name="hobby" value="王者"/>王者 <input type="checkbox" name="hobby" value="吃鸡" checked/>吃鸡 <input type="checkbox" name="hobby" value="飞车"/>飞车 <span id="afterHobby">*</span> </div> <!-- 生日 --> <div> <label for="birthday">生日</label> <input type="date" id="birthday" class="birthday" name="birthday"/> <span>*</span> </div> <!-- 身份证 --> <div> <label for="identityNo">身份证号</label> <input type="text" id="identityNo" class="identityNo" name="identityNo" placeholder="输入身份证"/> <span>*</span> </div> <!-- 电话 --> <div> <label for="phone">电话</label> <input type="tel" id="phone" name="phone" class="phone" placeholder="输入电话"/> <span>*</span> </div> <!-- 邮箱 --> <div> <label for="email">邮箱</label> <input type="email" id="email" name="email" class="email" placeholder="输入邮箱"/> <span>*</span> </div> <!-- 个人评价 --> <div class="resume"> <label for="resume">个人评价</label> <textarea id="resume" cols="20" rows="10" style="vertical-align: middle;"></textarea> <span>*</span> </div> <!-- 城市 --> <div> <label>所属城市</label> <select id="province" name="province"> <option value="ah">安徽</option> <option value="zj">浙江</option> <option value="js" selected>江苏</option> <option value="jx">江西</option> </select> 省 <select id="city" name="city"> <option value="hf">合肥</option> <option value="hz">杭州</option> <option value="nj" selected>南京</option> <option value="nc">南昌</option> </select> 市 <select id="district" name="district"> <option value="bh">滨湖</option> <option value="xh">西湖</option> <option value="jy" selected>建邺</option> <option value="lcq">老城</option> </select> 区 </div> <!-- 头像 --> <div> <label for="random">验证码</label> <input id="random" type="text" class="random" name="random" disabled/> <input id="reRandom" type="text" class="reRandom" name="reRandom"/> <span>*</span> </div> <!-- 头像 --> <div> <label for="pic">头像</label> <input id="pic" type="file" name="pic"/> <span>*</span> </div> <!-- 提交和重置 --> <div> <label> </label> <input type="submit" value="Submit"/> <input type="reset" value="Reset"/> </div> </form> </body> </html> <style> style: body { background: url("1000357.jpg") no-repeat; background-size: cover; } .register { width: 60%; margin: 0 auto; background-color: rgba(132, 170, 241, 0.2); padding: 10px; border-radius: 5px; } div { margin: 10px; height: 30px; } label { width: 80px; display: inline-block; text-align-last: justify; margin-right: 10px; } .userName, .password, .birthday, .phone, .email, .identityNo, .realName { height: 24px; width: 280px; padding-left: 10px; } .random, .reRandom { height: 24px; width: 130px; padding-left: 10px; text-align: center; } #resume { width: 288px; } .resume { height: 150px; margin-bottom: 20px; } select { height: 28px; } [type="submit"], [type="reset"] { border: none; width: 100px; text-align: center; background-color: green; color: white; line-height: 30px; height: 30px; border-radius: 5px; } .register span { color: red; } h1 { margin: 0 auto; padding: 0; color: #7f6b6b; width: 60%; } script: /** *使用String类和正则表达式进行表单验证 */ //随机验证码 let num = ""; //页面加载结束执行的函数 onload = function () { blurElement(); submitForm(); //爱好的change事件验证选择结果 let hobbyArr = document.querySelectorAll("input[name='hobby']"); for (let i = 0; i < hobbyArr.length; i++) { hobbyArr[i].onchange = function () { vailidateHobby(); }; } //验证图片 document.getElementById("pic").onchange = function () { vailidatePic(); }; //产生随机验证码 generateRandomNum(); }; //元素失去焦点时执行的验证函数 function blurElement() { //验证用户名 document.getElementById("userName").onblur = function () { vailidateUserName(); }; //验证密码 document.getElementById("password").onblur = function () { vailidatePassword() }; //验证真实姓名 document.getElementById("realName").onblur = function () { vailidateRealName(); }; //验证生日 document.getElementById("birthday").onblur = function () { vailidateBirthday(); }; //验证电话 document.getElementById("phone").onblur = function () { vailidatePhone(); }; //验证邮箱 document.getElementById("email").onblur = function () { vailidateEmail(); }; //验证简介 document.getElementById("resume").onblur = function () { vailidateResume(); }; //验证id document.getElementById("identityNo").onblur = function () { vailidateID(); }; } //表单提交执行的函数 function submitForm() { let form = document.getElementsByClassName("register")[0]; form.onsubmit = function (e) { //e.preventDefault(); let flag = vailidateUserName() & vailidateHobby() & vailidatePassword() & vailidateRealName() & vailidateBirthday() & vailidatePhone() & vailidateEmail() & vailidateResume() & vailidatePic() & vailidateID(); //alert(flag); return flag == 1 ? true : false; }; } //1、验证用户名:6-12位,字母开头,不能有_$之外的特殊字符,非空,唯一 function vailidateUserName() { let username = document.getElementById("userName"); let span = next(username); let value = username.value; let reg = /^[a-zA-Z][\w$]{5,11}$/; if (value == "") { span.innerHTML = "用户名不能为空"; span.style.color = "red"; return false; } else if (!reg.test(value)) { span.innerHTML = "用户名6-12位字母开头"; span.style.color = "red"; return false; } span.innerHTML = "用户名可用"; span.style.color = "green"; return true; } //2、验证密码:6-12位非空,必须包含大写字符,字母开头,非空 function vailidatePassword() { let password = document.getElementById("password"); let span = next(password); let value = password.value; let code = /^[a-zA-Z]$/; //非空 if (value == "") { span.innerHTML = "密码不能为空"; span.style.color = "red"; return false; } //首字母 let firstWord = value.charAt(0); if (!code.test(firstWord)) { span.innerHTML = "密码首位必须是字母"; span.style.color = "red"; return false; } //大写字符 hello let upCode = /^[A-Z]$/; for (let i = 0; i < value.length; i++) { if (upCode.test(value[i])) { break; } else if (i == value.length - 1) { span.innerHTML = "密码必须必须包含一位大写字母"; span.style.color = "red"; return false; } } //长度 if (value.length > 12 || value.length < 6) { span.innerHTML = "密码长度6-12位"; span.style.color = "red"; return false; } span.innerHTML = "密码可用"; span.style.color = "green"; return true; } //3、验证爱好:至少一个 function vailidateHobby() { let hobbyArr = document.querySelectorAll("input[name='hobby']"); let count = 0; for (let i = 0; i < hobbyArr.length; i++) { if (hobbyArr[i].checked) { count++; } } let span = document.getElementById("afterHobby"); if (count == 0) { span.innerHTML = "爱好至少选择一个"; span.style.color = "red"; return false; } span.innerHTML = "爱好选择正确"; span.style.color = "green"; return true; } //4、验证生日,非空 function vailidateBirthday() { let birthday = document.getElementById("birthday"); let span = next(birthday); let value = birthday.value; //2019-09-10 console.log(value); //非空 if (value == "") { span.innerHTML = "生日不能为空"; span.style.color = "red"; return false; } span.innerHTML = "生日正确"; span.style.color = "green"; return true; } //5、验证电话 1[3456789]\d{9} function vailidatePhone() { let phone = document.getElementById("phone"); let span = next(phone); let value = phone.value; let reg = /^1[3456789]\d{9}$/; if (value == "") { span.innerHTML = "电话不能为空"; span.style.color = "red"; return false; } if (value.charAt(0) !== '1') { span.innerHTML = "电话首位是1"; span.style.color = "red"; return false; } if (!(/^[3456789]$/.test(value.charAt(1)))) { span.innerHTML = "电话第2位是3456789任一位"; span.style.color = "red"; return false; } if (!reg.test(value)) { span.innerHTML = "电话11位数字"; span.style.color = "red"; return false; } span.innerHTML = "电话正确"; span.style.color = "green"; return true; } //6、验证邮箱 hao123@qq.com /hao123@qq.com.cn /hao123@qq.cn /hao123@qq.org /hao123@qq.net function vailidateEmail() { let email = document.getElementById("email"); let span = next(email); let value = email.value; let reg = /^[A-Za-z]\w+@[a-z0-9]{2,}(\.com|\.cn|\.com\.cn|\.net|\.org)$/; if (value == "") { span.innerHTML = "邮箱不能为空"; span.style.color = "red"; return false; } else if (!reg.test(value)) { span.innerHTML = "邮箱不合法,请参考:hao123@qq.com.cn"; span.style.color = "red"; return false; } span.innerHTML = "邮箱正确"; span.style.color = "green"; return true; } //7、验证个人评价 不能超200字,非空 function vailidateResume() { let resume = document.getElementById("resume"); let span = next(resume); let value = resume.value; if (value == "") { span.innerHTML = "个人评价不能为空!"; span.style.color = "red"; return false; } if (value.length > 200) { span.innerHTML = "内容不能超200字符!"; span.style.color = "red"; return false; } span.innerHTML = "输入正确!"; span.style.color = "green"; return true; } //8、验证头像(大小和类型) function vailidatePic() { //let arr = ["png", 'jpg', 'gif', 'bmp']; let pic = document.getElementById("pic"); let span = next(pic); let reg = /^png|jpg|gif|bmp$/; //获得当前图片的文件列表,是一个数组 let fileList = pic.files; console.log(fileList); let imgFile = fileList[0]; //必须处理的undefined异常 if (!imgFile) { span.innerHTML = "文件没有上传文件"; span.style.color = "red"; return false; } //获得imgFile的3个属性 let fileName = imgFile.name;//expo.png let fileSize = imgFile.size;//字节 1024byte = 1kB,1024kB = 1M //文件名的后缀 let suffix = fileName.substring(fileName.lastIndexOf(".") + 1);//png if (fileSize > (150 * 1024)) { span.innerHTML = "文件大小不能超150KB"; span.style.color = "red"; return false; } else if (!reg.test(suffix)) { span.innerHTML = "文件必须是图片格式"; span.style.color = "red"; return false; } span.innerHTML = "文件正确"; span.style.color = "green"; return true; } //9、验证身份证号码 18位 function vailidateID() { let id = document.getElementById("identityNo"); let span = next(id); //53 0102 1920 05 08 011X let value = id.value; //判断空 if (value == "") { span.innerHTML = "身份证号码不能为空"; span.style.color = "red"; return false; } //判断长度 if (value.length != 18) { span.innerHTML = "身份证号码长度18位"; span.style.color = "red"; return false; } //判断前17位数字 let reg = /^\d{17}$/; let str = value.substring(0, 17); if (!reg.test(str)) { span.innerHTML = "身份证号码前17位必须是数字"; span.style.color = "red"; return false; } //判断验证码 reg = /^[\dxX]$/; str = value.substring(17); if (!reg.test(str)) { span.innerHTML = "验证码必须是数字、x、X"; span.style.color = "red"; return false; } //判断区域码 let arr = [ "11", "12", "13", "14", "21", "22", "23", "21", "22", "23", "31", "32", "33", "34", "35", "36", "37", "41", "42", "43", "44", "45", "46", "50", "51", "52", "53", "54", "61", "62", "63", "64", "65", "81", "82", "83" ]; str = value.substring(0, 2); for (let i = 0; i < arr.length; i++) { if (str === arr[i]) { break; } else if (i == arr.length - 1) { span.innerHTML = "区域码不正确!"; span.style.color = "red"; return false; } } //判断年 [1900-now] let year = parseInt(value.substring(6, 10)); let now = new Date().getFullYear(); if (year > now || year < 1900) { span.innerHTML = "年份必须在1900-" + now + "之间"; span.style.color = "red"; return false; } //判断月 [1-12] let month = parseInt(value.substring(10, 12)); if (month > 12 || month < 1) { span.innerHTML = "月份必须在1-12之间!"; span.style.color = "red"; return false; } //判断日 [1-28][1-29][1-30][1-31] let days = 0; //2月的天数,根据year是否闰年 if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) { //闰年 days = 29; } else { //平年 days = 28; } let arrDays = [31, days, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; let date = parseInt(value.substring(12, 14)); if (date < 1 || date > arrDays[month - 1]) { span.innerHTML = "日必须在1-" + arrDays[month - 1] + "之间"; span.style.color = "red"; return false; } span.innerHTML = "身份证号码正确"; span.style.color = "green"; return true; } //10、验证真实姓名:汉字[2,50]|字母[3-50] function vailidateRealName() { let realName = document.getElementById("realName"); let span = next(realName); let value = realName.value; let reg = /^([\u4e00-\u9fa5]{2,50})|([A-Za-z]{3,50})$/; if (value == "") { span.innerHTML = "真实姓名不能为空"; span.style.color = "red"; return false; } else if (!reg.test(value)) { span.innerHTML = "真实姓名汉字[2,50]或者字母[3-50]"; span.style.color = "red"; return false; } span.innerHTML = "姓名可用"; span.style.color = "green"; return true; } //验证随机验证码 function vailidateRandom () { //作业:完成今天所有表单验证 //还有此处验证功能:just do it! } //t元素后面的兄弟元素 function next(t) { return t.nextElementSibling; } //产生随机验证码 function generateRandomNum() { for (let i = 0; i < 6; i++) { num += parseInt(Math.random() * 10); } document.getElementById("random").value = num; }