@fekit/idcard
Version:
中国身份证号详细信息获取
97 lines (88 loc) • 3.07 kB
text/typescript
import { provinceObj, cityObj, areaObj } from './constant';
const _provinceObj: any = provinceObj;
const _cityObj: any = cityObj;
const _areaObj: any = areaObj;
// 获取生日,年龄,星座
const getBirth = (year: number = 0, month: number = 0, day: number = 0) => {
// 生日
const birthday = year + '-' + (month > 9 ? month : '0' + month) + '-' + (day > 9 ? day : '0' + day) || '';
const date = new Date();
const curMonth = date.getMonth() + 1;
const curDay = date.getDate();
// 年龄
let age = date.getFullYear() - year;
if (curMonth < month || (curMonth === month && curDay < day)) {
age--;
}
// 生肖
const zodiacEnums = ['', '鼠', '牛', '虎', '兔', '龙', '蛇', '马', '羊', '猴', '鸡', '狗', '猪'];
const zodiac = zodiacEnums[Number((year % 12) + 9 <= 12 ? (year % 12) + 9 : (year % 12) + 9 - 12) || 0];
// 星座
const constellationEnums = ['', '水瓶座', '双鱼座', '白羊座', '金牛座', '双子座', '巨蟹座', '狮子座', '处女座', '天秤座', '天蝎座', '射手座', '摩羯座'];
const a = [
{ min: 120, max: 218 },
{ min: 219, max: 320 },
{ min: 321, max: 419 },
{ min: 420, max: 520 },
{ min: 521, max: 621 },
{ min: 622, max: 722 },
{ min: 723, max: 822 },
{ min: 823, max: 922 },
{ min: 923, max: 1023 },
{ min: 1024, max: 1122 },
{ min: 1123, max: 1221 },
];
let constellation = 12;
const md = `${month}${day < 10 ? '0' + day : day}`;
a.forEach((item: any, idx: number) => {
const { min = 0, max = 0 } = item;
if (md >= min && md <= max) {
constellation = idx + 1;
}
});
// 星座
return { birthday, age, zodiac, constellation: constellationEnums[Number(constellation) || 0] };
};
// 获取省市区
const getArea = (p: string = '', c: string = '', a: string = '') => {
const areaCode = p + c + a;
const province = {
code: p + '0000',
text: _provinceObj[p] || '',
};
const city = {
code: p + c + '00',
text: _cityObj[p + c] || '',
};
const area = {
code: areaCode,
text: _areaObj[p + c + a] || '',
};
const adreass = province.text + city.text + area.text;
return { province, city, area, adreass };
};
const idcard = (id: string = '') => {
// 判断是一代还是二代身份证并格式化
const _id = id.length === 15 ? id.substring(0, 6) + '19' + id.substring(6) + '0' : id;
const info = _id.match(/(\d{2})(\d{2})(\d{2})(\d{4})(\d{2})(\d{2})(\d{2})(\d{1})(\d|X)/);
if (!info || (info && Number(info[5]) > 12)) {
return false;
} else {
const { birthday = '', age = '', zodiac = '', constellation = '' } = getBirth(Number(info[4]), Number(info[5]), Number(info[6]));
const gender = parseInt(info[8]) % 2 === 1 ? '男' : '女';
const { province = '', city = '', area = '', adreass = '' } = getArea(info[1], info[2], info[3]);
return {
gender,
birthday,
province,
area,
adreass,
city,
cardText: '大陆',
age,
zodiac,
constellation,
};
}
};
export default idcard;