在网页开发过程中,对表单的操作通常会用Javascript来验证输入字段的有效性,比如验证输入字符的类型、电话号码格式、身份证、电子邮件等等。 以下为整理封装好的一些验证函数,希望给有需要的人在使用上带来方便(本文末带有下载链接) //检查身份证格式 String.prototype.isIDCard = function() { var vCid = this.trim(); var vSum = 0; var vReg = /^([\d]{17}[xX\d]|[\d]{15})$/; var vCity = '|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|'; if (!vReg.test(vCid)) return false; if(vCity.indexOf(parseInt(vCid.substr(0,2))) == '-1') return false; vCid = vCid.replace(/[xX]$/i, 'a'); if (vCid.length == 18) { vBirthday = vCid.substr(6, 4) + '/' + Number(vCid.substr(10, 2)) + '/' + Number(vCid.substr(12, 2)); } else { vBirthday = '19' + vCid.substr(6, 2) + '/' + Number(vCid.substr(8, 2)) + '/' + Number(vCid.substr(10, 2)); } var vDate = new Date(vBirthday); if (vBirthday != (vDate.getFullYear() + '/' + (vDate.getMonth() + 1) + '/' + vDate.getDate())) return false; if (vCid.length == 18) { for(var i = 17 ; i >= 0 ; i--) vSum += (Math.pow(2, i) % 11) * parseInt(vCid.charAt(17 - i), 11); if(vSum % 11 != 1) return false; } return true; } //检查电子邮箱格式 String.prototype.isMail = function() { var mail = this.trim(); var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/; return reg.test(mail); } //检查是否是数字 String.prototype.isNumber = function() { var oNum = this.trim(); var strP = /^\d+(\.\d+)?$/; if(!strP.test(oNum)) return false; try{ if(parseFloat(oNum)!=oNum) return false; } catch(ex) { return false; } return true; } //检查电话号码(可带区号或不带区号,区号用-分隔) String.prototype.isPhone = function() { var phoneNumber = this.trim(); var reg = /^((0\d{2,3})-)?(\d{7,8})(-(\d{3,}))?$/; return reg.test(phoneNumber); } //检查手机号码 String.prototype.isMobile = function() { var mobile = this.trim(); var reg = /^(?:13\d|15\d)\d{5}(\d{3}|\*{3})$/; return reg.test(mobile); } //检查IP地址 String.prototype.isIp = function() { var strIp = this.trim(); var IPReg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/; return IPReg.test(strIp); } //验证日期格式(2014-11-07),暂不支持带时间的日期 String.prototype.isDate = function() { var datestr = this.trim(); var regex = /^(\d{4})-(\d{1,2})-(\d{1,2})$/; if( regex.test(datestr) ){ var noArr = datestr.split("-"); var year = eval(noArr[0]); var month = eval(noArr[1]); var day = eval(noArr[2]); if ( year < 1 || month < 1 || month > 12 || day < 1 || day > 31) { return false; } if ((month == 4 || month == 6 || month == 9 || month == 11) && day > 30){ return false; } if (month == 2){ if ((year % 4 != 0) && day > 29) { return false; } if (year % 4 == 0){ if(year % 100 == 0 && year % 400 != 0 && day > 29){ return false; } else if (day > 28){ return false; } } } return true; }else{ return false; } } 使用方法(页面上导入下载下来的js文件): <script type="text/javascript"> var test_str = "2014-11-07"; //要验证的字符串 if(test_str.isDate()){ alert("success"); }else{ alert("fail"); } </script>
文章来源 CODETC,欢迎分享,转载请注明地址:
http://www.codetc.com/article-37-1.html
|