在前端表单中,我们会经常用到正则来达到验证功能,下面例举几个常用的匹配例子。
- 用户名正则
//用户名正则,5到20位(字母,数字,下划线,减号)var uPattern = /^[a-zA-Z0-9_-]{5,20}$/;//输出 trueconsole.log(uPattern.test("caibaojian"));
- 手机号正则
//手机号正则var mPattern = /^1[34578]\d{9}$/; //输出 trueconsole.log(mPattern.test("15852586258"));
- Email正则
//Email正则var ePattern = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;//输出 trueconsole.log(ePattern.test("1501160961@qq.com"));
- 密码强度正则
//密码强度正则,最少6位,包括至少1个大写字母,1个小写字母,1个数字,1个特殊字符var pPattern = /^.*(?=.{6,})(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*? ]).*$/;//输出 trueconsole.log("=="+pPattern.test("caibaojian#"));
- 整数正则
//正整数正则var posPattern = /^\d+$/;//负整数正则var negPattern = /^-\d+$/;//整数正则var intPattern = /^-?\d+$/;//输出 trueconsole.log(posPattern.test("42"));//输出 trueconsole.log(negPattern.test("-42"));//输出 trueconsole.log(intPattern.test("-42"));
- 数字正则
//正数正则var posPattern = /^\d*\.?\d+$/;//负数正则var negPattern = /^-\d*\.?\d+$/;//数字正则var numPattern = /^-?\d*\.?\d+$/;console.log(posPattern.test("42.2"));console.log(negPattern.test("-42.2"));console.log(numPattern.test("-42.2"));
- qq号正则
//QQ号正则,5至11位var qqPattern = /^[1-9][0-9]{4,10}$/;//输出 trueconsole.log(qqPattern.test("1501160961"));
- 微信号正则
//微信号正则,6至20位,以字母开头,字母,数字,减号,下划线var wxPattern = /^[a-zA-Z]([-_a-zA-Z0-9]{5,19})+$/;//输出 trueconsole.log(wxPattern.test("wanglong_com"));
- 车牌号正则
//车牌号正则var cPattern = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/;//输出 trueconsole.log(cPattern.test("粤B39006"));
- 包含中文正则
//包含中文正则var cnPattern = /[\u4E00-\u9FA5]/;//输出 trueconsole.log(cnPattern.test("蔡宝坚"));