正则验证、计算身份证

1.校验15、18位身份证
const regCart = /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/;

缺点:未校验2月份的天数不超过28


2.校验手机号码
const regExp = /^1(3|4|5|7|8)\d{9}$/;

3.根据身份证计算出生日期、年龄、性别
calculateCard(str) {
  const ret = {
    birthday: null,
    age: null,
    gender: null,
  };
  const len = str.length;
  if (len === 15 || len === 18) {
    // 计算出生日期 - birthday
    if (len === 18) {
      ret.birthday = `${str.substr(6, 4)}-${str.substr(10, 2)}-${str.substr(12, 2)}`;
    }
    if (len === 15) {
      ret.birthday = `19${str.substr(6, 2)}-${str.substr(8, 2)}-${str.substr(10, 2)}`;
    }
    // 计算年龄 - age
    const ageVal = new Date(ret.birthday);
    const nowDateTime = new Date();
    ret.age = nowDateTime.getFullYear() - ageVal.getFullYear();
    // 月、天的差异
    if (nowDateTime.getMonth() < ageVal.getMonth() ||
     (nowDateTime.getMonth() === ageVal.getMonth() && nowDateTime.getDate() < ageVal.getDate())) {
      ret.age -= 1;
    }
    // 计算性别 - gender
    ret.gender = (parseInt(str.substr(16, 1), 10) % 2 === 1) ? '男' : '女';
  }
  return ret;
},
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值