前端校验身份证号正则,校验规则省份、年月日,包含15位校验(完整)

 //省份对应的代号      ```
const city = {
    11: '北京',
    12: '天津',
    13: '河北',
    14: '山西',
    15: '内蒙古',
    21: '辽宁',
    22: '吉林',
    23: '黑龙江 ',
    31: '上海',
    32: '江苏',
    33: '浙江',
    34: '安徽',
    35: '福建',
    36: '江西',
    37: '山东',
    41: '河南',
    42: '湖北 ',
    43: '湖南',
    44: '广东',
    45: '广西',
    46: '海南',
    50: '重庆',
    51: '四川',
    52: '贵州',
    53: '云南',
    54: '西藏 ',
    61: '陕西',
    62: '甘肃',
    63: '青海',
    64: '宁夏',
    65: '新疆',
    71: '台湾',
    81: '香港',
    82: '澳门',
    91: '国外'
};
const regCity = `(${Reflect.ownKeys(city).join('|')})`;
//当前日期
const currentDate = new Date();
const year = String(currentDate.getFullYear()).split('');
const month = String(currentDate.getMonth() + 1).split('');
const day = String(currentDate.getDate()).split('');
//处理小于10的月份和天数
if (month.length < 2) {
    month.unshift('0');
}
if (day.length < 2) {
    day.unshift('0');
}
//校验时间月、日
const regDay = `(((0[13578]|1[02])([0-2]\d|3[0-1]))|(02[0-2]\d)|((0[469]|11)([0-2]\d|30)))`;
//校验十五位身份证号
const reg15 = `(^${regCity}\\d{4}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{2}$)`;
//当前月校验
const currentYearMonth = `${month[0]}${month[1]}${day[0]==0? `0[1-${day[1]}]`:`([0-${day[0]-1}][1-9])|(${day[0]}[0-${day[1]}])`}`;
/***当前年其他月份校验*/
//当前月小于十月份校验
const min10Month = `0[1-${month[1] - 1}](0[1-9]|[1-2]\d|3[0-1])`;
//当前月大于等于十月份校验
const max10Month = `(0[1-9](0[1-9]|[1-2]\d|3[0-1]))${month[1]==0? '':`|(1[0-${month[1] - 1}](0[1-9]|[1-2]\d|3[0-1]))`}`;
const currentYearOtherMonth = month[0] == 0? min10Month:max10Month;
/***组装身份证号校验规则*/
//当前年
const currentYear = `${year[0]}${year[1]}${year[2]}${year[3]}`;
//当前年份校验,当前月份是一月份只使用 currentYearMonth 校验月份
const currentYearReg = `(${currentYear}${ month[0] == 0 && month[1] == 1? '(':`(${currentYearOtherMonth}|`}${currentYearMonth}))`;
//其他年份校验
const regMillenniumMinBirthday = `${year[0]}[0-${year[1]}](([0-${year[2] - 1<0? 0:year[2] - 1}]\d)|(${year[2]}[0-${year[3] - 1 < 0? 0:year[3] - 1}]))`;
const otherYearReg = `((([0-${year[0] - 1}]\d{3})|(${regMillenniumMinBirthday}))${regDay})`;
const regBirthday18 = `(${otherYearReg}|${currentYearReg})`;
const reg18 = `(^${regCity}\d{4}${regBirthday18}\d{3}[0-9Xx]$)`;
const reg = new RegExp(`${reg15}|${reg18}`);

你可能感兴趣的:(前端,正则,javascript)