结合element-plus表单校验身份证号是否正确,并提取出生日期及年龄

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;
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值