1. 程式人生 > >javascript判斷身份證號資訊是否正確的方法

javascript判斷身份證號資訊是否正確的方法

    網站註冊經常需要用到實名認證需要使用者或者玩家提供身份證資訊,在提交到伺服器之前需要做一個正確性的判斷,可以用一個js函式實現

checkRealCard:function(strRealCard){
            var getAppendZore = function(strNum){
                if(strNum < 10){ strNum = '0'+strNum; }
                return strNum;
            };
            var tmpRealCard = strRealCard;
            var tmpCityCode = { 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 (tmpRealCard == ''){ return '身份證號碼不能為空'; }

            // Check real card.
            var tmpRegx=new RegExp(/(^\d{15}$)|(^\d{17}(\d|x|X)$)/i);
            if (!tmpRegx.exec(tmpRealCard)){
                return '身份證號碼長度必須正確,請核對!';
            }

            // Check 15 length.
            var tmpRegx=new RegExp(/^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/);
            if (tmpRegx.exec(tmpRealCard)){
                tmpBirthday = '19'+tmpRealCard.substring(6,8)+'-'+tmpRealCard.substring(8,10)+'-'+tmpRealCard.substring(10,12);
            }else{
                tmpSum = 0;

                tmpRealCard = tmpRealCard.replace(/x|X$/i,"a");

                for (var i = 17; i >= 0; i--){
                    tmpSum += (Math.pow(2, i) % 11) * parseInt(tmpRealCard.charAt(17 - i), 11);
                }

                if (tmpSum % 11 != 1) {
                    return '身份證號碼不符相關標準,請核對!';
                }

                tmpBirthday = tmpRealCard.substring(6,10)+'-'+tmpRealCard.substring(10,12)+'-'+tmpRealCard.substring(12,14);
            }

            // Check City.
            if (tmpCityCode[parseInt(tmpRealCard.substring(0, 2))] == null){
                return '身份證號碼證件地區未知,請核對!';
            }

            // Check Birthday.
            var tmpDate = new Date(tmpBirthday.replace(/-/g, "/"));
            if (tmpBirthday != (tmpDate.getFullYear()+'-'+ getAppendZore(tmpDate.getMonth()+1)+'-'+ getAppendZore(tmpDate.getDate()))){
                return '身份證號碼出生日期非法,請核對!';
            }

            //alert(tmpBirthday);
            return true;
        },