常用正则校验

SakurArrivederci大约 2 分钟正则表达式正则表达式

常用正则校验

记录项目中常用的正则表达式或校验方法

身份证

function validateIdCard(idCard) {
  var city = {
    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 retflag = false;
  var idCardLength = idCard.length;
  if (idCardLength == 15 || idCardLength == 18) {
    if (city[idCard.substr(0, 2)] == undefined) {
      return false;
    }
    if (idCardLength == 15) {
      pattern = /^\d{15}$/;
      if (pattern.exec(idCard) == null) {
        return false;
      }
      var birth = parseInt("19" + idCard.substr(6, 2));
      var month = idCard.substr(8, 2);
      var day = idCard.substr(10, 2);
      var d = new Date(birth, parseFloat(month) - 1, parseFloat(day));
      if (d.getYear() != parseFloat(idCard.substr(6, 2)) ||
        d.getMonth() != parseFloat(month) - 1 ||
        d.getDate() != parseFloat(day)) {
        return false;
      }
    } else {
      pattern = /^\d{17}(\d|x|X)$/;
      if (pattern.exec(idCard) == null) {
        return false;
      }
      var birth = parseInt(idCard.substr(6, 4));
      var month = idCard.substr(10, 2);
      var day = idCard.substr(12, 2);
      var d = new Date(birth, parseFloat(month) - 1, parseFloat(day));
      if (d.getFullYear() != parseFloat(idCard.substr(6, 4)) ||
        d.getMonth() != parseFloat(month) - 1 ||
        d.getDate() != parseFloat(day)) {
        return false;
      }
      var sum = 0;
      var ids = idCard.split("");
      var idCardWi = [
        7,
        9,
        10,
        5,
        8,
        4,
        2,
        1,
        6,
        3,
        7,
        9,
        10,
        5,
        8,
        4,
        2
      ];
      var idCardY = [
        1,
        0,
        "X",
        9,
        8,
        7,
        6,
        5,
        4,
        3,
        2
      ];
      for (var i = 0; i < 17; i++) {
        sum += parseInt(ids[i]) * idCardWi[i];
      }
      var idCardMod = sum % 11;
      if (idCardY[idCardMod] != ids[17].toUpperCase()) {
        return false;
      }
    }
    retflag = true;
  }
  return retflag;
}

金额

var reg = /^(?=.*\d)\d{0,7}(?:\.\d{0,2})?$/;
console.log(reg.test("2000")); // true
console.log(reg.test("12.5")); // true
console.log(reg.test("0.01")); // true
console.log(reg.test("123456789")); // false
console.log(reg.test("12.123")); // false
console.log(reg.test(".12")); // false

手机号

/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/

邮箱

/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/
上次编辑于: