1、表单校验身份证是否正确
const validatorIdCard = async (rule: any, value: any, callback: any) => {
// 正则表达式,支持18位和15位身份证号码
// console.log("身份证", value);
const idCardRegex = /^[1-9]\d{5}(18|19|20)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])\d{3}(\d|X|x)?$/;
// console.log("身份证-值", idCardRegex.test(value));
if (!value) {
return callback(new Error(t("validate.required")));
} else if (!idCardRegex.test(value)) {
return callback(new Error("身份证格式不正确"));
} else {
return callback();
}
};
2、如果身份证格式正确则提取出生日期
// 获取出生日期
const getBirthDateFromID = (idCard: any) => {
// 检查身份证号长度是否有效
if (idCard.length !== 18 && idCard.length !== 15) return "";
let birthYear, birthMonth, birthDay;
if (idCard.length === 18) {
// 18位身份证:第7到10位为年份,第11到12位为月份,第13到14位为日期
birthYear = idCard.substring(6, 10);
birthMonth = idCard.substring(10, 12);
birthDay = idCard.substring(12, 14);
} else if (idCard.length === 15) {
// 15位身份证:第7到8位为年份,第9到10位为月份,第11到12位为日期
birthYear = "19" + idCard.substring(6, 8); // 假设15位身份证对应19xx年
birthMonth = idCard.substring(8, 10);
birthDay = idCard.substring(10, 12);
}
// 返回出生日期字符串,格式为 YYYY-MM-DD
return `${birthYear}-${birthMonth}-${birthDay}`;
};
3、如果身份证格式正确则提取年龄
// 获取年龄
const getAgeFromID = (idCard: any) => {
// 根据身份证号长度判断是否有效
if (idCard.length !== 18 && idCard.length !== 15) return "";
// 对于15位身份证号码,转换为18位
let birthYear;
if (idCard.length === 15) {
birthYear = "19" + idCard.substring(6, 8); // 假设15位身份证号对应19xx年
} else {
birthYear = idCard.substring(6, 10);
}
let birthMonth = idCard.substring(10, 12);
let birthDay = idCard.substring(12, 14);
// 获取当前日期对象
let currentDate = new Date();
let currentYear = currentDate.getFullYear();
let currentMonth = currentDate.getMonth() + 1; // 月份从0开始,所以加1
let currentDay = currentDate.getDate();
// 计算年龄
let age = currentYear - birthYear;
// 检查是否过了今年的生日
if (currentMonth < birthMonth || (currentMonth === birthMonth && currentDay < birthDay)) {
age--;
}
return age;
};