JS身分証番号チェック


function identityCodeValid (code){
    var city={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:"  ",
        83:"  ",81:"  ",82:"  ",91:"   "};
    var tip = "";
    var pass= true;

    if(!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)){
        tip = "        ";
        pass = false;
    }

    else if(!city[code.substr(0,2)]){
        tip = "      ";
        pass = false;
    }
    else{
        //18               
        if(code.length == 18){
            code = code.split('');
            //∑(ai×Wi)(mod 11)
            //    
            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;
            var ai = 0;
            var wi = 0;
            for (var i = 0; i < 17; i++)
            {
                ai = code[i];
                wi = factor[i];
                sum += ai * wi;
            }
            var last = parity[sum % 11];
            if(last != code[17]){
                tip = "     ";
                pass =false;
            }
        }else{
            pass =false;
        }
    }
    return pass;
}