效果圖:
代碼:
<!DOCTYPE html><html><head> <meta charset="UTF-8"> <title></title> <style> *{ padding:0; margin:0} </style></head><body> <form id="f" method="post" action="regSave.php"> 社會安全號碼碼:<input id="txtId" type="text" value="612301197000000000"><br/> 電話號碼:<input id="txtPhone" type="text" value="18991274261"><br/> 電郵:<input id="txtEmail" type="text" value="7701037@qq.com"><br/> <input type="submit" value="註冊"> </form> <div id="msgBox"> </div></body></html><script type="text/javascript">//策略模式的代碼開始var validator = { //寫驗證類型(描述了所有類型資料的驗證規則) types:{}, //驗證的資料類型(針對不同類型的資料,選擇不同的驗證規則) config:{}, //存放所有錯誤資訊的數組 errMsg:[], //驗證函式(傳入若干資料,一次性驗證完成) //類比一下data參數 validator:function (data) { this.errMsg=[]; for(let key in data){ if(!this.types[this.config[key]].validator(data[key])){ this.errMsg.push(this.types[this.config[key]].errorMsg); } } }};//策略模式的代碼結束//給策略模式裡增加策略開始validator.types.isEmail ={ validator:function(value){ var reg = /^[\w\.]+@\w+(\.com|\.net|\.cn|\.com\.cn)$/; return reg.test(value); }, errorMsg:"郵箱格式不合法,合法的郵箱格式如:7701037@qq.com"};validator.types.isPhone ={ validator:function(value){ var reg = /^1[34578]\d{9}$/; return reg.test(value); }, errorMsg:"手機格式不合法,長度為11位的數字,而且必須以1開頭"};validator.types.isId ={ validator:function(value){ var reg = /^[1-9]\d{16}[\dX]$/; return reg.test(value); }, errorMsg:"社會安全號碼碼不合法"}//給策略模式裡增加策略結束//“資料類型”和驗證策略的對應關係validator.config={ "id":"isId", "email":"isEmail", "phone":"isPhone",};function $(id) { return document.getElementById(id);}//進行表單驗證function checkAll(){ //1、組織資料成json格式(擷取文字框的內容) var d = { "email":$("txtEmail").value, "phone":$("txtPhone").value, "id":$("txtId").value }; validator.validator(d); if(validator.errMsg.length>0){ //把所有的錯誤資訊放入到div裡(msgBox) let htmlStr=""; for(let i in validator.errMsg){ htmlStr+= validator.errMsg[i]+"<br/>"; } $("msgBox").innerHTML = htmlStr; return false; }else{ return true; }}window.onload = function(){ $("f").onsubmit = function(){ /* 寫法一: //1、前端驗證 if(!checkAll()){ //2、不通過則不提交 return false;//阻止事件的預設行為 } */ //寫法二: return checkAll(); }}</script>