身份证号码校验、生成、解析
功能预览
身份证生成
身份证号:
身份证解析
身份证号:
代码实现
身份证校验
js
// 计算校验值
export const computedChinaIDCardLastChar = (str) => {
let total = 0;
const numbers = str.split("");
for (let i = 0; i < 17; i++) {
total += parseInt(numbers[i], 10) * (Math.pow(2, 17 - i) % 11);
}
let lastDigit = (12 - (total % 11)) % 11;
if (lastDigit === 10) {
lastDigit = "X";
}
return lastDigit.toString().toUpperCase();
};
// 校验身份证是否合法
export function checkIdentity(str) {
let reg18 =
/^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
let reg15 =
/^([1-6][1-9]|50)\d{4}\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}$/;
// 身份证号位数为15或18位
if (![15, 18].includes(str && str?.length)) {
return false;
} else {
return (
(reg18.test(str) && computedChinaIDCardLastChar(str) == str[17]) || reg15.test(str)
);
}
}
身份证解析
text
110102 2000 01 01 1466
1-6位是省市区代码
7-14位是出生年月日
15、16为顺序码
17位表示性别,奇数为男,偶数为女,
18位为校验位,数字+X组成,X表示10
js
import { provinceListObject } from "@localData/province.js";
import { cityListObject } from "@localData/city.js";
import { areaListObject } from "@localData/area.js";
import dayjs from "dayjs";
// 身份证号
const identity = ref("");
// 省市区
const province = provinceListObject?.[identity.value.substring(0, 2)]?.label;
const city = cityListObject?.[identity.value.substring(0, 4)]?.label;
const area = areaListObject?.[identity.value.substring(0, 6)]?.label;
const birthday = dayjs(identity.value.substring(6, 14)).format("YYYY-MM-DD");
const sex = identity.value.substring(16, 17) % 2 ? "男" : "女";
js
// @localData/province.js
// 省市区数据格式
{
11: {
value: "11",
label: "北京市",
},
12: {
value: "12",
label: "天津市",
},
// ...
}
身份证生成
身份证组成原理及校验位算法见上方内容。
js
// 创建身份证号表单
const createIdForm = reactive({
areaCode: null,
date: null,
sex: null,
});
// 被创建的身份证号
const beCreatedId = ref("");
// 根据表单生成身份证
const onCreateId = () => {
// 生成一个随机顺序码
const order = "" + randomNum(0, 9) + randomNum(0, 9);
// 根据性别随机生成对应的奇偶数
const sexNum = createIdForm.sex ? randomEvenIn10() : randomOddIn10();
// 拼装前17位数
let pre17Char = `${createIdForm.areaCode}${createIdForm.date}${order}${sexNum}`;
// 通过前17位计算生成校验位;
beCreatedId.value = pre17Char + computedChinaIDCardLastChar(pre17Char);
};
// 随机身份证数据并生成
const randomCreateId = () => {
// 随机选一个地区,areaListArray全部数据在【完整代码】中
createIdForm.areaCode = areaListArray[randomNum(0,
// 随机一个出生日期
areaListArray.length - 1)].value;
createIdForm.date = `${dayjs(randomNum(0, Date.now())).format("YYYYMMDD")}`;
// 随机性别
createIdForm.sex = randomNum(0, 1);
onCreateId();
};
完整代码
身份证省code数据
https://eryaoss.ischuan.cn/public/province.js
身份证市code数据
https://eryaoss.ischuan.cn/public/province.js