1. 程式人生 > >身份證號碼的規則及驗證原理

身份證號碼的規則及驗證原理

<script language="javascript">
    <!--
    var powers=new Array("7","9","10","5","8","4","2","1","6","3","7","9","10","5","8","4","2");
    var parityBit=new Array("1","0","X","9","8","7","6","5","4","3","2");
    var sex="male";
    //校驗身份證號碼的主呼叫

    function validId(obj){
        var _id=obj.value;
        if
(_id=="")return;
        var _valid=false;
        if(_id.length==15){
            _valid=validId15(_id);
        }else if(_id.length==18){
            _valid=validId18(_id);
        }
        if(!_valid){
            alert("身份證號碼有誤,請檢查!");
            obj.focus();
            return;
        }
        //設定性別

        var
sexSel=document.getElementById("sex");
        var options=sexSel.options;
        for(var i=0;i<options.length;i++){
            if(options[i].value==sex){
                options[i].selected=true;
                break;
            }
        }
    }    
    //校驗18位的身份證號碼

    function validId18(_id){
        _id=
_id+"";
        var _num=_id.substr(0,17);
        var _parityBit=_id.substr(17);
        var _power=0;
        for(var i=0;i< 17;i++){
            //校驗每一位的合法性

            if(_num.charAt(i)<'0'||_num.charAt(i)>'9'){
                return false;
                break;
            }else{
                //加權

                _power+=parseInt(_num.charAt(i))*parseInt(powers[i]);
                //設定性別

                if(i==16&&parseInt(_num.charAt(i))%2==0){
                    sex="female";
                }else{
                    sex="male";
                }
            }
        }
        //取模

        var mod=parseInt(_power)%11;
        if(parityBit[mod]==_parityBit){
            return true;
        }
        return false;
    }
    //校驗15位的身份證號碼

    function validId15(_id){
        _id=_id+"";
        for(var i=0;i<_id.length;i++){
            //校驗每一位的合法性

            if(_id.charAt(i)<'0'||_id.charAt(i)>'9'){
                return false;
                break;
            }
        }
        var year=_id.substr(6,2);
        var month=_id.substr(8,2);
        var day=_id.substr(10,2);
        var sexBit=_id.substr(14);
        //校驗年份位

        if(year<'01'||year >'90')return false;
        //校驗月份

        if(month<'01'||month >'12')return false;
        //校驗日

        if(day<'01'||day >'31')return false;
        //設定性別

        if(sexBit%2==0){
            sex="female";
        }else{
            sex="male";
        }
        return true;
    }
    //-->

</script>
<input type="text" onblur="validId(this)" maxlength=18 size=18>
<select id="sex">
    <option value="male"></option>
    <option value="female"></option>