javascript常用正则表达式汇总
/** * 检验各种规则 * @param str 检验的内容 * @param ctype 预设的检验规则 字符串[ * empty, 检验是否为空 * telphone, 座机手机号码 * allphone, 所有手机号码 * ydphone, 移动手机号码 * ltphone, 联通手机号码 * dxphone, 电信手机号码 * email, 邮箱 * url, 网址 * cn, 汉字 * image, 图片格式 * emscode, 邮政编码 * isempty, 检查是否为空 * isint, 整数 * isfloat, 判断是否为正小数 * isnumber, 判断为实数 * words, 判断是否为英文字母 * wordsandnum, 判断是否为字母+数字 * wordsandnumanddownline, 判断是否由数字、26个英文字母或者下划线组成的字符串 * qq, qq检验 * personcard18, 身份证18位 * personcard15, 身份证15位 * ] * @param regex 自定义表达式 传入格式例如:^\-?[1-9]+\d*$ * * @description ctype 与 regex 只能有一个为空 * 如 checkobjectbyregex(测试中文, cn); // 判断中文 * 如 checkobjectbyregex(测试中文, null, ^[\u4e00-\u9fa5]+$); // 自定义表达式正则 * @return {boolean} */function checkobjectbyregex(str, ctype, regex) { /** * 定义验证各种格式类型的正则表达式对象 */ var regexs = { telphone: (/^((\(\d{3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}$/), //座机手机号码 allphone: (/^((13[0-9])|(14[57])|(15[0-9])|(17[678])|(18[0-9]))[0-9]{8}$/), //所有手机号码 ydphone: (/^((13[4-9])|(15[012789])|147|178|(18[23478]))[0-9]{8}$/), //移动手机号码 ltphone: (/^((13[0-2])|(145)|(15[56])|(176)|(18[56]))[0-9]{8}$/), //联通手机号码 dxphone: (/^((133)|(153)|(177)|(180)|(181)|(189))[0-9]{8}$/), //电信手机号码 email: (/^([a-za-z0-9_-])+@([a-za-z0-9_-])+((\.[a-za-z0-9_-]{2,3}){1,2})$/),//邮箱 url: (/(?:https|http|ftp|rtsp|mms):\/\/.+\/[\w]+\.[\w]+/), //网址 cn: (/^[\u4e00-\u9fa5]+$/i), //汉字 image: (/\.jpg$|\.jpeg$|\.png$/i), //图片格式 emscode: (/^[1-9]\d{5}$/), //邮政编码 isint: (/^(\-)?[1-9]+\d*$/), //整数 isfloat: (/^[0-9]+\.?[0-9]*$/), //判断是否为正小数 isnumber: (/^[-\+]?\d+(\.\d+)?$/), //判断为实数 words: (/^[a-za-z]+$/), //判断是否为英文字母 wordsandnum: (/^[a-za-z0-9]+$/), //判断是否为字母+数字 wordsandnumanddownline: (/^\w+$/), //判断是否由数字、26个英文字母或者下划线组成的字符串 qq: (/^[1-9]\d{4,11}$/), //qq personcard18: (/^(\d{6})()?(\d{4})(\d{2})(\d{2})(\d{3})(\d|x)$/), //身份证18位 personcard15: (/^(\d{6})()?(\d{2})(\d{2})(\d{2})(\d{3})$/) //身份证15位 }; var nreg; if (str == null || typeof(str) == undefined) { str = ; } if (ctype != null && typeof(ctype) != undefined) { if (ctype == isempty) { str = $.trim(str); if (str != null && typeof(str) != undefined && str != ) { return false; } else return true; } nreg = regexs[ctype]; if (str == null || str == ) return false; //输入为空,认为是验证通过 // 针对 18位身份证单独处理 if (ctype == 'personcard18') { var ary = str.match(regexs[ctype]); if (!(parseint(ary[3]) >= 1900)) return false; var d = new date(ary[3] + / + ary[4] + / + ary[5]); var istrue = d.getfullyear() == ary[3] && (d.getmonth() + 1) == ary[4] && d.getdate() == ary[5]; return istrue; } // 针对 15位身份证单独处理 if (ctype == 'personcard15') { var ary = str.match(regexs[ctype]); var d = new date(19 + ary[3] + / + ary[4] + / + ary[5]); var istrue = d.getyear() == ary[3] && (d.getmonth() + 1) == ary[4] && d.getdate() == ary[5]; return istrue; } } else { // 自定义正则表达式处理 if (regex != null && typeof(regex) != undefined) { nreg = new regexp(regex); } else { return false; } } return nreg.test(str);}
以上所述就是本文的全部内容了,希望大家能够喜欢。
