前注:在数据添加的时候很多地方都会涉及到数据的合法性验证,所以有必要提炼成为一个工具。今天偶然间点错网页,弹出一个游戏界面,本来是想看怎么实现的背景音乐的加载的,结果看到一个注册页面的验证JS,所以这里摘录以备以后使用。在此感谢我佛山人!
/************************************************* Validator v1.05 code by 我佛山人 wfsr@msn.com *************************************************/ Validator = { unValid : /[\x22-\x27\x2A\x2F\x3C\x3E\x3F\x40\x5B-\x5E\x60\x7B\x7D\u201D\u201C\u203B\u2192\u25CB\u25CE\u25C6\u25C7\u25A0\u2584\u2586\u2605\u2606\u3010\u3011\uFFE5]/g, isValid : function(str){return !this.unValid.test(str);}, Valid : "this.isValid(value)", Require : /\S+/, Email : /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, Phone : /^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/, Mobile : /^((\(\d{2,3}\))|(\d{3}\-))?1((3|5|8)\d{9}|47\d{8})$/, IsTel : function(str){return this.Phone.test(str) || this.Mobile.test(str);}, Tel : "this.IsTel(value)", Url : /^http(s){0,1}:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/, IdCard : "this.IsIdCard(value)", Currency : /^\d+(\.\d+)?$/, Number : /^\d+$/, Zip : /^\d{6}$/, QQ : /^[1-9]\d{4,11}$/, isIM : function(str){return this.QQ.test(str) || this.Email.test(str);}, Positive : /^\d+(\.\d+)?/, Integer : /^[-\+]?\d+$/, Double : /^[-\+]?\d+(\.\d+)?$/, English : /^[A-Za-z]+$/, Chinese : /^[\u0391-\uFFE5]+$/, Username : /^[a-z]\w{3,}$/i, UnSafe : /^(([A-Z]*|[a-z]*|\d*|[-_\~!@#\$%\^&\*\.\(\)\[\]\{\}<>\?\\\/\'\"]*)|.{0,5})$|\s/, IsSafe : function(str){return !this.UnSafe.test(str);}, SafeString : "this.IsSafe(value)", IM : "this.isIM(value)", Filter : "this.DoFilter(value, getAttribute('accept'))", Limit : "this.limit(value.length,getAttribute('min'), getAttribute('max'))", LimitB : "this.limit(this.LenB(value), getAttribute('min'), getAttribute('max'))", Date : "this.IsDate(value, getAttribute('min'), getAttribute('format'))", Repeat : "value == document.getElementsByName(getAttribute('to'))[0].value", Range : "getAttribute('min') < (value|0) && (value|0) < getAttribute('max')", Compare : "this.compare(value,getAttribute('operator'),getAttribute('to'))", CompareObj : "this.compare(value,getAttribute('operator'),obj[getAttribute('to')].value)", Custom : "this.Exec(value, getAttribute('regexp'))", Group : "this.MustChecked(getAttribute('name'), getAttribute('min'), getAttribute('max'))", ErrorItem : [document.forms[0]], ErrorMessage : ["以下原因导致提交失败:\t\t\t\t"], Validate : function(theForm, mode){ var obj = theForm || event.srcElement; var count = obj.elements.length; this.ErrorMessage.length = 1; this.ErrorItem.length = 1; this.ErrorItem[0] = obj; for(var i=0;i<count;i++) { with(obj.elements[i]){ var _dataType = getAttribute("dataType"); if(typeof(_dataType) == "object") continue; this.ClearState(obj.elements[i]); if(getAttribute("require") == "false" && value == "") continue; _dataType = _dataType.split(" "); var fflag = true; for(k = 0, kl = _dataType.length; k < kl; k++) { if(typeof(this[_dataType[k]]) == "undefined") continue; if(!fflag) break; switch(_dataType[k]) { case "IdCard" : case "Date" : case "Repeat" : case "Range" : case "Compare" : case "CompareObj" : case "Custom" : case "Group" : case "Limit" : case "LimitB" : case "SafeString" : case "Filter" : case "IM" : case "Tel" : case "Valid" : if(!eval(this[_dataType[k]])) { this.AddError(i, getAttribute("msg")); fflag = false; } break; default : if(!this[_dataType[k]].test(value)) { this.AddError(i, getAttribute("msg")); fflag = false; } break; } } } } if(this.ErrorMessage.length > 1) { mode = mode || 1; var errCount = this.ErrorItem.length; switch(mode){ case 2 : for(var i=1;i<errCount;i++) this.ErrorItem[i].style.color = "red"; case 1 : try{ top.message.show(this.ErrorMessage.join("<br />"),null,function(){ try{ Validator.ErrorItem[1].focus(); } catch(e){ } }); } catch(e){ alert(this.ErrorMessage.join("\n")); try{ Validator.ErrorItem[1].focus(); } catch(e){ } } break; if(top.message) { message.show(this.ErrorMessage.join("<br />"), null, function(){ try { Validator.ErrorItem[1].focus(); } catch (e) {} }); } else { alert(this.ErrorMessage.join("\n")); if(this.ErrorItem[1].style.display != 'none' && this.ErrorItem[1].type != 'hidden') this.ErrorItem[1].focus(); } break; case 3 : for(var i=1;i<errCount;i++){ try{ var span = document.createElement("SPAN"); span.id = "__ErrorMessagePanel"+i; span.style.color = "red"; if(this.ErrorItem[i].nextSibling) this.ErrorItem[i].parentNode.insertBefore(span, this.ErrorItem[i].nextSibling); else this.ErrorItem[i].parentNode.appendChild(span); span.innerHTML = this.ErrorMessage[i].replace(/\d+:/,""); this.ErrorItem[i].className = 'err'; } catch(e){alert(e.description);} } this.ErrorItem[1].focus(); break; default : alert(this.ErrorMessage.join("\n")); break; } return false; } return true; }, limit : function(len,min, max){ min = min || 0; max = max || Number.MAX_VALUE; return min <= len && len <= max; }, LenB : function(str){ return str.replace(/[^\x00-\xff]/g,"**").length; }, ClearState : function(elem) { with(elem){ if(style.color == "red") style.color = ""; if(className == 'err') className = ""; var lastNode = nextSibling; if(lastNode && /^__ErrorMessagePanel/.test(lastNode.id)) parentNode.removeChild(lastNode); } }, AddError : function(index, str){ this.ErrorItem[this.ErrorItem.length] = this.ErrorItem[0].elements[index]; this.ErrorMessage[this.ErrorMessage.length] = this.ErrorMessage.length + ":" + str; }, Exec : function(op, reg){ return new RegExp(reg,"g").test(op); }, compare : function(op1,operator,op2){ if(this.Double.test(op1) && this.Double.test(op2)) { op1 = parseInt(op1, 10); op2 = parseInt(op2, 10); } switch (operator) { case "NotEqual": return (op1 != op2); case "GreaterThan": return (op1 > op2); case "GreaterThanEqual": return (op1 >= op2); case "LessThan": return (op1 < op2); case "LessThanEqual": return (op1 <= op2); default: return (op1 == op2); } }, MustChecked : function(name, min, max){ var groups = document.getElementsByName(name); var hasChecked = 0; min = min || 1; max = max || groups.length; for(var i=groups.length-1;i>=0;i--) if(groups[i].checked) hasChecked++; return min <= hasChecked && hasChecked <= max; }, DoFilter : function(input, filter) { return new RegExp("^.+\.(?=EXT)(EXT)$".replace(/EXT/g, filter.split(/\s*,\s*/).join("|")), "gi").test(input); }, IsIdCard : function(idcard){ idcard = idcard.toUpperCase(); var area={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",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:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"} var idcard,Y,JYM; var S,M; var idcard_array = new Array(); idcard_array = idcard.split(""); if(area[parseInt(idcard.substr(0,2))]==null) return false; switch(idcard.length){ case 15: if ((parseInt(idcard.substr(6,2))+1900) % 4 == 0 || ((parseInt(idcard.substr(6,2))+1900) % 100 == 0 && (parseInt(idcard.substr(6,2))+1900) % 4 == 0 )){ ereg = /^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$/;//测试出生日期的合法性 } else{ ereg = /^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$/;//测试出生日期的合法性 } if(ereg.test(idcard)) return true; else return false; break; case 18: if ( parseInt(idcard.substr(6,4)) % 4 == 0 || (parseInt(idcard.substr(6,4)) % 100 == 0 && parseInt(idcard.substr(6,4))%4 == 0 )){ ereg = /^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$/;//闰年出生日期的合法性正则表达式 } else{ ereg = /^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$/;//平年出生日期的合法性正则表达式 } if(ereg.test(idcard)){ S = (parseInt(idcard_array[0]) + parseInt(idcard_array[10])) * 7 + (parseInt(idcard_array[1]) + parseInt(idcard_array[11])) * 9 + (parseInt(idcard_array[2]) + parseInt(idcard_array[12])) * 10 + (parseInt(idcard_array[3]) + parseInt(idcard_array[13])) * 5 + (parseInt(idcard_array[4]) + parseInt(idcard_array[14])) * 8 + (parseInt(idcard_array[5]) + parseInt(idcard_array[15])) * 4 + (parseInt(idcard_array[6]) + parseInt(idcard_array[16])) * 2 + parseInt(idcard_array[7]) * 1 + parseInt(idcard_array[8]) * 6 + parseInt(idcard_array[9]) * 3 ; Y = S % 11; M = "F"; JYM = "10X98765432"; M = JYM.substr(Y,1); if(M == idcard_array[17]) return true; else return false; } else return false; break; default: return false; break; } }, IsDate : function(op, formatString){ formatString = formatString || "ymd"; var m, year, month, day; switch(formatString) { case "ymd" : m = op.match(new RegExp("^((\\d{4})|(\\d{2}))([-./])(\\d{1,2})\\4(\\d{1,2})$")); if(m == null ) return false; day = m[6]; month = m[5]*1; year = (m[2].length == 4) ? m[2] : GetFullYear(parseInt(m[3], 10)); break; case "dmy" : m = op.match(new RegExp("^(\\d{1,2})([-./])(\\d{1,2})\\2((\\d{4})|(\\d{2}))$")); if(m == null ) return false; day = m[1]; month = m[3]*1; year = (m[5].length == 4) ? m[5] : GetFullYear(parseInt(m[6], 10)); break; default : break; } if(!parseInt(month)) return false; month = month==0 ?12:month; var date = new Date(year, month-1, day); return (typeof(date) == "object" && year == date.getFullYear() && month == (date.getMonth()+1) && day == date.getDate()); function GetFullYear(y){return ((y<30 ? "20" : "19") + y)|0;} } }
纸上得来终觉浅,绝知此事要躬行。