- 由于前面六位代表省市区县太复杂了,我就没进行检验。主要是省市区县太多了,不好验证。
- 其中的校验码运算,参考百度关于身份证。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript">
function check() {
var Id=document.getElementById('ID').value;
if(lengthcheck(Id)&&birthcheck(Id)&&codecheck(Id))
{
alert("身份证号正确");
showdata(Id);
}
}
function lengthcheck(id) {
if(id.length==18)
{ return true;}
else{
document.getElementById('error').innerHTML='位数错误'
return false;
}
}
function birthcheck(id) {
var year=id.substr(6,4);
var month=id.substr(10,2);
var day=id.substr(12,2);
var a=new Date();
if(year>a.getFullYear()||month==0||month>13||day>31)
{
document.getElementById('error').innerHTML='出生日期错误'
return false;
}else {
return true;
}
}
function codecheck(id) {
Wi=[7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2]
Xi=[1,0,"X",9,8,7,6,5,4,3,2]
var aIdCard=id.split("");
var sum=0;
for (var i = 0; i < Wi.length; i++) {
sum+=Wi[i]*aIdCard[i]; //线性加权求和
};
var index=sum%11;//求模,可能为0~10,可求对应的校验码是否于身份证的校验码匹配
if (Xi[index]==aIdCard[17].toUpperCase()) {
return true;
}else {
document.getElementById('error').innerHTML='校验码错误'
return false;
}
}
function showdata(id) {
var year=id.substr(6,4);
var month=id.substr(10,2);
var day=id.substr(12,2);
var sex=id.substr(16,1);
var a=new Date();
document.getElementById('year').innerHTML=year;
document.getElementById('month').innerHTML=month;
document.getElementById('day').innerHTML=day;
var show=document.getElementById('show');
document.getElementById('error')
show.innerHTML=d;
if(sex%2!=0)
{
document.getElementById('sex').innerHTML='男性';
}else {
document.getElementById('sex').innerHTML='女性';
}
document.getElementById('age').innerHTML=a.getFullYear()-year;
}
</script>
<style type="text/css">
.content{
width: 300px;
height: 200px;
margin-left: 500px;
margin-top: 100px;
background-color: #cccccc;
padding-left: 30px;
padding-top: 20px;
}
</style>
</head>
<body>
<div class="content">
<tr>请输入身份证号码<input type="text" id="ID" autofocus="autofocus" placeholder="十八位有效数字"> <input type="submit" value="提交" onclick="check()"><span id="error"></span></tr><br>
输出<span id="show"></span><br>
出生年月:<span id="year"></span>年<span id="month"></span>月<span id="day"></span>日<br>
性别:<span id="sex"></span><br>
年龄:<span id="age"></span>
</div>
</body>
</html>
运行图