校验身份是否合法,18位与15位都校验:
//idNo 身份证号
export function validIDNum(idNo){
if(!idNo){
return false;
}
let headChar = idNo.substr(0,1);
//身份证不能以7,8,9开头,长度只能为15或18
if(
(idNo.length != 15 && idNo.length !=18)|| headChar == '7' || headChar == '8' || headChar == '9'
){
return false
}else{
let reg = /^[0-9]*$/;
if(idNo.length == 15){
if(!reg.test(idNo)){
return false;
}
}else if(!validIDNum18(idNo)){
return false;
}else{
}
return true;
}
}
校验18位身份证:
// cid 为传入的18位身份证号码
export function validIDNum18(cid){
let arrExp = [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2]; //加因子
let arrValid = [1,0,'X',9,8,7,6,5,4,3,2]; //校验码
if(/^\d{17}|x$/i.test(cid)){
let sum = 0;
idx;
for(let i=0; i < cid.length - 1;i++){
//对前17位数字与权值乘积求和
sum += parseInt(cid.substr(i,1),10) * arrExp[i];
}
//计算模
idx = sum % 11;
//检验第18是否与校验码相等
return arrValid[idx] == cid.substr(17,1).toUpperCase();
}else{
return false;
}
}
15位身份证升级18位:
export function getID18ByID15(id){
if(id.length == 15){
let id18 = "";
id18 = id.substring(0,6) + "19" + id.substring(6);
let Wi = [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2];
let lasnum = ["1","0","X","9","8","7","6","5","4","3","2"]
let k,
TotalmulAiWi = 0;
for(k=0;k<17;k++){
TotalmulAiWi = TotalmulAiWi + parseInt(id18.substring(k,k+1)) * Wi[k];
}
let modValue = TotalmulAiWi % 11;
id18 = id18 + lasnum[modValue];
return id18;
}else{
return id;
}
}
根据身份证号获取出生日期:
//根据身份证获取出生日期
export function getBirthdayTime(id){
let year = IdCard.substring(6,10);
let month = IdCard.substring(10,12);
let day = IdCard.substring(12,14);
let birthdayDate = new Date(year,parseFloat(month)-1,parseFloat(day));
return birthdatDate
}
根据身份证获取年龄:
export function getAgeByIDCard(idCard){
idCard = idCard.replace(/ /g,""); //处理中间空格
let fromday = "",today = new Date();
if(idCard.length == 18){
fromday = idCard.substring(6,14)
}else if(idCard.length == 15){
let y = idCard.substring(6,8);
let m = idCard.substring(8,10);
let d = idCard.substring(10,12);
let temp_date = new Date(y,parseFloat(m)-1,parseFloat(d));
fromday = temp_date.getFullYear() + m + d;
}else{}
let year = today.getFullYear(),month = today,getMonth() + 1,date = today.getDate();
let they = fromday.substring(0,4),them = fromday.substring(4,2),thed = fromday.substring(6,2);
if(month - them < 0 || ((month - them ==0)&&(date - thed <0))) return year - they - 1;
else return year - they;
}