示例方法
/**
* 识别是否是身份证,且校验出生年月日是否正确
* @param idCard
* @returns {string|null}
*/
getBirthday(idCard) {
//身份证号码正则表达式
var idCardReg = /(^\d{15}$)|(^\d{17}([0-9]|X)$)/;
//如果不是有效的身份证号码则返回null
if (!idCardReg.test(idCard)) {
return null;
}
//获取出生年月日
var birthday = '';
// eslint-disable-next-line eqeqeq
if (idCard.length == 15) {
birthday = '19' + idCard.slice(6, 12);
} else {
birthday = idCard.slice(6, 14);
}
//将年月日分别提取出来
var year = birthday.slice(0, 4);
var month = birthday.slice(4, 6);
var day = birthday.slice(6, 8);
//判断年月日是否正确
var date = new Date(year, parseInt(month) - 1, day);
// eslint-disable-next-line eqeqeq
if (date.getFullYear() != year || date.getMonth() + 1 != month || date.getDate() != day) {
return null;
}
//返回出生年月日
return year + '-' + month + '-' + day;
},