/*** 检验身份证号码<br/>* 15位:ddddddyymmddxxp<br/>* 18位:ddddddyyyymmddxxxy<br/>* @param cardNum 身份证号码 string* @param needAlertError 是否需要弹出错误提示信息* @return true/false*/function checkIDCardNumber ( cardNum , needAlertError ) {//默认不弹出错误提示信息needAlertError = !! needAlertError || false ;if ( typeof cardNum != 'string' ) {if ( needAlertError ) {alert ( "参数cardNum格式错误" );}return false ;}//身份证号码长度为15位或18位if ( cardNum . length != 15 && cardNum . length != 18 ) {if ( needAlertError ) {alert ( "身份证号码位数不对" );}return false ;}//15位身份证号码全为数字,18位也全为数字或17位数字,并以字符X结尾if ( ! /^\d{15}$|(^\d{17}[0-9Xx]$)/ . test ( cardNum )) {if ( needAlertError ) {alert ( "身份证号码含有非法字符" );}return false ;}// 地址编码var province = {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 : "国外" };if ( ! province [ cardNum . substring ( 0 , 2 )]) {if ( needAlertError ) {alert ( "身份证号码地区非法" );}return false ;}//出生日期var birthday = cardNum . length == 15 ? ( "19" + cardNum . substring ( 6 , 12 )) : cardNum . substring ( 6 , 14 );if ( ! /(19)|(20)\d{6}/ . test ( birthday )) {if ( needAlertError ) {alert ( "身份证号码出生日期超出范围或格式错误" );}return false ;}var year = parseInt ( birthday . substring ( 0 , 4 ));var month = parseInt ( birthday . substring ( 4 , 6 )) - 1 ;var day = parseInt ( birthday . substring ( 6 ));var newBirthday = new Date ( year , month , day );var formatedBirthday = "" + newBirthday . getFullYear ();formatedBirthday += ( newBirthday . getMonth () < 9 ? "0" : "" ) + ( newBirthday . getMonth () + 1 );formatedBirthday += ( newBirthday . getDate () < 10 ? "0" : "" ) + newBirthday . getDate ();//身份证中如包含如下格式的日期将不能通过校验:20150230、20150735if ( birthday != formatedBirthday ) {if ( needAlertError ) {alert ( "身份证号码出生日期超出范围或格式错误" );}return false ;}//校验位 ∑(ai×Wi)(mod 11)if ( cardNum . length == 18 ) {//加权因子var factor = [ 7 , 9 , 10 , 5 , 8 , 4 , 2 , 1 , 6 , 3 , 7 , 9 , 10 , 5 , 8 , 4 , 2 ];//校验位var parity = [ 1 , 0 , 'X' , 9 , 8 , 7 , 6 , 5 , 4 , 3 , 2 ];var sum = 0 ;for ( var i = 0 ; i < 17 ; i ++ ){sum += cardNum [ i ] * factor [ i ];}if ( parity [ sum % 11 ] != cardNum [ 17 ]){if ( needAlertError ) {alert ( "身份证号码校验位错误" );}return false ;}}return true ;}
JavaScript检验身份证号码
最新推荐文章于 2024-02-05 18:03:32 发布