身份证校验

function validateCardNo(cardNo) {
  if (!cardNo) {
    return false
  }
  // 定义判别用户身份证号的正则表达式(15位或者18位,最后一位可以为字母)
  const regularExpression = /(^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}$)/

  const matches = regularExpression.test(cardNo)

  // 判断第18位校验值
  if (matches) {
    if (cardNo.length == 18) {
      // 校验行政区划码
      // http://c.gb688.cn/bzgk/gb/showGb?type=online&hcno=C9C488FD717AFDCD52157F41C3302C6D
      const areaCode = cardNo.substring(0, 6)
      const flag = validateAreaCode(areaCode)
      if (!flag) {
        return false
      }

      const charArray = cardNo.split('')
      // 前十七位加权因子
      const idCardWi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
      // 这是除以11后,可能产生的11位余数对应的验证码
      const idCardY = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
      let sum = 0
      for (let i = 0; i < idCardWi.length; i += 1) {
        const current = charArray[i]
        const wi = idCardWi[i]
        const count = current * wi

        console.log(`第${i + 1}位 字符为:${current}, 加权因子为:${wi},乘积为:${count}`)
        sum += count
      }
      const idCardLast = charArray[17]
      const idCardMod = sum % 11
      if (idCardY[idCardMod].toUpperCase() === idCardLast.toUpperCase()) {
        return true
      }
      return false
    } else {
      console.log('身份证号长度不为18位')
    }
  }
  return matches
}

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值