正则验证身份证号是否正确(15位和18位)

正则验证身份证号(案例是微信小程序)

先创建一个idVerification.js的js类型文件,方便后续引入

const isValidIdCard = (idCard)=>{
    // 初步格式校验
    if (!(/^\d{15}$|^\d{17}[\dXx]$/.test(idCard))) {
      return false;
    }
    // 分别处理15位和18位身份证号
    const isFifteenDigit = idCard.length === 15;
    const birthdayStr = isFifteenDigit ? `19${idCard.slice(6, 12)}` : idCard.slice(6, 14);
    if (!validateBirthday(birthdayStr)) {
      return false;
    }
    if (!isFifteenDigit && !validateChecksum(idCard)) {
      return false;
    }
    // 校验地区码
    if (!validateAreaCode(idCard.slice(0, 2))) {
      return false;
    }
    return true;
}
const validateBirthday = (birthdayStr)=>{
  const year = parseInt(birthdayStr.slice(0, 4), 10);
  const month = parseInt(birthdayStr.slice(4, 6), 10) - 1; // JavaScript中的月份是0-11
  const day = parseInt(birthdayStr.slice(6, 8), 10);

  const date = new Date(year, month, day);
  return date.getFullYear() === year && date.getMonth() === month && date.getDate() === day;
}
//校验码校验
const validateChecksum = (idCard)=>{
  const checksumWeights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
  const checksumDigits = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];

  const sum = idCard.slice(0, 17).split('').reduce((acc, digit, index) => {
    return acc + parseInt(digit) * checksumWeights[index];
  }, 0);
  const mod = sum % 11;
  const lastChar = idCard[17].toUpperCase();
  return checksumDigits[mod] === lastChar;
}
//地区码校验
const validateAreaCode = (areaCode)=>{
  const validAreaCodes = new Set([
    '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'
  ]);
  return validAreaCodes.has(areaCode);
}

module.exports = isValidIdCard;

在需要验证的文件中中引入

import idVerification from "../../utils/idVerification";

使用该方法

   if(!idVerification(this.data.id_card)){
      wx.showToast({
        title: '请输入正确的身份证号',
        icon: 'none',
        duration: 2000
      })
    }

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值