js获取身份证信息
js获取身份证信息<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js获取身份证信息</title>
</head>
<body>
身份证号码:<input type="text" value="" id="txtCardID" onblur="getInfo()">
年龄:<input type="text" value="" id="txtAge">
出生日期:<input type="text" value="" id="txtBirth">
性别:<input type="text" value="" id="txtSex">
<input type="button" value="获取身份证信息" onclick="getInfo()">
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.slim.min.js"></script>
<script>
function checkId(pId) {
//检查身份证号码
var arrVerifyCode = ;
var Wi = ;
var Checker = ;
if(pId.length != 15 && pId.length != 18) {
//return "身份证号共有15位或18位"
alert("身份证号共有15位或18位")
return
}
var Ai = pId.length == 18 ? pId.substring(0, 17) : pId.slice(0, 6) + "19" + pId.slice(6, 16);
if(!/^\d+$/.test(Ai)) {
//return "身份证除最后一位外,必须为数字!"
alert("身份证除最后一位外,必须为数字!")
return
}
var yyyy = Ai.slice(6, 10), mm = Ai.slice(10, 12) - 1, dd = Ai.slice(12, 14);
var d = new Date(yyyy, mm, dd), now = new Date();
var year = d.getFullYear(), mon = d.getMonth(), day = d.getDate();
if(year != yyyy || mon != mm || day != dd || d > now || year < 1800) {
//return "身份证输入错误!"
alert("身份证格式错误!")
return
}
for(var i = 0, ret = 0; i < 17; i++) {
ret += Ai.charAt(i) * Wi
}
Ai += arrVerifyCode;
return pId.length == 18 && pId != Ai ? alert("身份证格式错误!") : Ai;
}
function getInfo() {
//获取输入身份证号码
var ic = $("#txtCardID").val();
ic = checkId(ic);
if(isNaN(ic)) return;
var ic = String(ic);
//获取出生日期
var birth = ic.substring(6, 10) + "-" + ic.substring(10, 12) + "-" + ic.substring(12, 14);
$("#txtBirth").val(birth);
//获取性别
var gender = ic.slice(14, 17) % 2 ? "1" : "2"; // 1代表男性,2代表女性
gender === "1" ? $("#txtSex").val("男") : $("#txtSex").val("女")
/*var sexOption = document.getElementsByName("rabSex");
for(var i = 0; i < sexOption.length; i++) {
if(sexOption.value == gender) {
sexOption.checked = true;
break;
}
}*/
//获取年龄
var myDate = new Date();
var month = myDate.getMonth() + 1;
var day = myDate.getDate();
var age = myDate.getFullYear() - ic.substring(6, 10) - 1;
if(ic.substring(10, 12) < month || ic.substring(10, 12) == month && ic.substring(12, 14) <= day) {
age++;
}
$("#txtAge").val(age);
}
</script>
</body>
</html>
页:
[1]