正则验证身份证号(案例是微信小程序)
先创建一个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
})
}