今天(2018-04-09)在整理正则表达时,有一个关于身份证号码的正则匹配。最简单的不动脑子的匹配方式为:^[1-9]\d{16}[\d|x]$,但是这样很容易伪造一个身份证号来骗过电脑,于是加强版的正则匹配为:
^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$
虽然加强版的正则匹配能过滤掉大部分不靠谱的身份证号码,但仍存在漏网之鱼,比如我创造了一个符合它正则规则的号码:123456180011116578(纯属构造)
从上图我们看到,这个构造的身份证号码验证通过了。所以光用正则匹配不能完全判断输入的身份证号是否为正确的值。
后来在百度百科里看到了身份证号的验证规则:
于是开始动手写了验证的js代码:
<!DOCTYPE>
<html><head><title>身份证号码验证规则</title><script src="http://cdn.gbtags.com/datatables/1.10.5/js/jquery.js"></script> <script>$(function(){$('.btn').click(function(){let orginnumber =$('.number').val();let partn = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;//先用正则判断是否为正确的格式if (!partn.exec(orginnumber)){alert('请检查你输入的身份证个式是否正确!');}else{let number = [...orginnumber]; //es6语法,利用...将变量的值转成数组。let ration= new Array("7","9","10","5","8","4","2","1","6","3","7","9","10","5","8","4","2");//系数let ration22= new Array("1","0","x","9","8","7","6","5","4","3","2");let sum=0;console.log(ration);for(let i=0;i<number.length-1;i++){sum=number[i]*ration[i]+sum;console.log(i);}let mod = sum%11;if(ration22[mod]==number[17]){alert('正确');}else{alert('不正确');}}})})
</script></head><body><div><lable for="input">输入身份证号码:</lable><input type="text" class="number"/><button class="btn">提交</button></div></body>
</html>