正則驗證、計算身份證

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;
},
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章