身份证验证函数 php javascript版

2011-10-12 14:20  1658人阅读  评论 (0)

今天用到了,顺便吧自己些的身份证衍生函数给贴出来分享给大家,希望能喜欢。

身份证算法相关link

php版:

function cnid($cnid){
    $cnid = strtolower($cnid);
    if(!preg_match('/^\d{17}[\dx]$/', $cnid)){
        return false;
    }

    $xs = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
    $cl = array(1, 0, 'x', 9, 8, 7, 6, 5, 4, 3, 2);

    $cs = str_split($cnid);
    //var_export($cs);
    $check = array_pop($cs);
    foreach($xs as $i=>$x){
        $cs[$i] *= $x;
    }
    $num = array_sum($cs);
    $ys = $num % 11;

    return $check == $cl[$ys];
}

js版:

function cnid(cnid){
    cnid = cnid.toLowerCase();
    if(!/^\d{17}[\dx]$/.test(cnid)){
        return false;
    }

    var xs = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
    var cl = [1, 0, 'x', 9, 8, 7, 6, 5, 4, 3, 2];

    var cs = cnid.split('');
    var check = cs.pop();
    var num = 0;
    for(var i=0; i<cs.length; i++){
        num += cs[i] * xs[i];
    }
    var ys = num % 11;

    return check == cl[ys];
}