// 身份證驗證
Vue.prototype.$checkIdCard = function(idCard){
let _this = this;
let bbd = ''; // 出生日期
let sex = ''; // 性別
let canPass = true;
idCard = idCard.toUpperCase(); // 轉大寫
let len = idCard.length;
let 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:"國外"};
//1. 判斷長度
if (len !== 15 && len !== 18){
_this.$toast.error('身份證號長度不正確!');
canPass = false;
}
//2. 身份證號碼爲15位或者18位,15位時全爲數字,18位前17位爲數字,最後一位是校驗位,可能爲數字或字符X。
if (!(/(^\d{15})|(^̲\d{17}([0-9]|X))/.test(idCard))) {
_this.$toast.error('身份證號格式錯誤!');
canPass = false;
}
//3. 地址碼
if (!city[idCard.substr(0,2)]){
_this.$toast.error('身份證號地址碼不正確!');
canPass = false;
}
let re;
//4. 生日
if (len === 15) {
re = new RegExp(/^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/);
let arrSplit = idCard.match(re);
//檢查生日日期是否正確
let birth = new Date('19' + arrSplit[2] + '/' + arrSplit[3] + '/' +arrSplit[4]);
let isBirth = (birth.getYear() === Number(arrSplit[2])) && ((birth.getMonth() + 1) === Number(arrSplit[3])) && (birth.getDate() === Number(arrSplit[4]));
if (!isBirth) {
_this.$toast.error('身份證號出生日期不對!');
canPass = false;
}
bbd = birth;
} else if (len === 18) {
re = new RegExp(/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/);
let arrSplit = idCard.match(re);
//檢查生日日期是否正確
let birth = new Date(arrSplit[2] + "/" + arrSplit[3] + "/" +arrSplit[4]);
let isBirth = (birth.getFullYear() === Number(arrSplit[2])) && ((birth.getMonth() + 1) === Number(arrSplit[3]))
&& (birth.getDate() === Number(arrSplit[4]) && (birth.getTime()<new Date().getTime()));
if (!isBirth) {
_this.$toast.error('身份證號出生日期不對!');
canPass = false;
} else {
//檢驗18位身份證的校驗碼是否正確。
//校驗位按照ISO 7064:1983.MOD 11-2的規定生成,X可以認爲是數字10。
let valnum;
let arrInt = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
let arrCh = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
;
let nTemp = 0, i;
for (i = 0; i < 17; i++) {
nTemp += idCard.substr(i, 1) * arrInt[i];
}
valnum = arrCh[nTemp % 11];
if (valnum !== idCard.substr(17, 1)) {
_this.$toast.error('身份證號校驗碼不正確!');
canPass = false;
}
}
bbd = birth;
}
// 如果身份驗證通過,計算出生年月,性別
if(canPass == true){
bbd = bbd.getFullYear() + '-' + Number(bbd.getMonth() + 1) + '-' + bbd.getDate();
let arr_fix = bbd.split('-');
if(arr_fix[1].length == 1){
arr_fix[1] = '0' + arr_fix[1];
}
if(arr_fix[2].length == 1){
arr_fix[2] = '0' + arr_fix[2];
}
bbd = arr_fix[0] + '-' + arr_fix[1] + '-' + arr_fix[2];
if(idCard.length == 18){
sex = idCard.charAt(idCard.length - 2)
}else{
sex = idCard.charAt(idCard.length - 1)
}
if(sex%2 == 1){
sex = '男';
}else{
sex = '女';
}
}
// canPass true時位驗證通過,false時位驗證失敗
return {
canPass: canPass,
birthday: bbd, // 返回生日
sex: sex // 返回性別
};
},
Vue學習筆記-身份證規則校驗
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.