1. 程式人生 > 其它 >身份證號驗證 正則

身份證號驗證 正則

身份證號驗證 正則

 /**
     * @description: 身份證號校驗
     * @param {*}num  身份證號的值
     * @return {*}
     */
    checkMobileIDNumber(num) {
      if (!num) {
        return
      }
      num = num.toUpperCase()
      //身份證號碼為15位或者18位,15位時全為數字,18位前17位為數字,最後一位是校驗位,可能為數字或字元X。
      if (!/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(num)) {
        return '(身份證號有誤)'
      }
      //校驗位按照ISO 7064:1983.MOD 11-2的規定生成,X可以認為是數字10。
      //下面分別分析出生日期和校驗位
      let len, re
      len = num.length
      if (len == 15) {
        re = new RegExp(/^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/)
        let arrSplit = num.match(re)

        //檢查生日日期是否正確
        let dtmBirth = new Date('19' + arrSplit[2] + '/' + arrSplit[3] + '/' + arrSplit[4])
        let bCorrectDay
        bCorrectDay = dtmBirth.getYear() == Number(arrSplit[2]) && dtmBirth.getMonth() + 1 == Number(arrSplit[3]) && dtmBirth.getDate() == Number(arrSplit[4])
        if (!bCorrectDay) {
          return '(出生日期有誤)'
        } else {
          //將15位身份證轉成18位
          //校驗位按照ISO 7064:1983.MOD 11-2的規定生成,X可以認為是數字10。
          let arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2)
          let arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2')
          let nTemp = 0,
            i
          num = num.substr(0, 6) + '19' + num.substr(6, num.length - 6)
          for (i = 0; i < 17; i++) {
            nTemp += num.substr(i, 1) * arrInt[i]
          }
          num += arrCh[nTemp % 11]
          return ''
        }
      }
      if (len == 18) {
        re = new RegExp(/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/)
        let arrSplit = num.match(re)

        //檢查生日日期是否正確
        let dtmBirth = new Date(arrSplit[2] + '/' + arrSplit[3] + '/' + arrSplit[4])
        let bCorrectDay
        bCorrectDay = dtmBirth.getFullYear() == Number(arrSplit[2]) && dtmBirth.getMonth() + 1 == Number(arrSplit[3]) && dtmBirth.getDate() == Number(arrSplit[4])
        if (!bCorrectDay) {
          return '(出生日期有誤)'
        } else {
          //檢驗18位身份證的校驗碼是否正確。
          //校驗位按照ISO 7064:1983.MOD 11-2的規定生成,X可以認為是數字10。
          let valnum
          let arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2)
          let arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2')
          let nTemp = 0,
            i
          for (i = 0; i < 17; i++) {
            nTemp += num.substr(i, 1) * arrInt[i]
          }
          valnum = arrCh[nTemp % 11]
          if (valnum != num.substr(17, 1)) {
            return '(校驗碼有誤)'
          }
          return ''
        }
      }
      return ''
    },