Regular verification of the second generation ID number of Js

The number of the first generation ID card is 15 digits. Since January 1, 2013, we have stopped using the first generation ID card in China.

Second generation ID card No.:

  • 1-6 digits: Code of administrative division.
    • 1, 2 digits, code of the province (municipality directly under the central government, autonomous region);
    • 3-digit, 4-digit, city (autonomous prefecture) code;
    • 5, 6, code of the district (county, Autonomous County, county-level city);
  • 7-14: the year, month and day of birth
  • 15-16 digits: Code of local police station
  • 17: gender. Odd (1, 3, 5, 7, 9) male, even (2, 4, 6, 8, 0) female
  • 18 bits: check bit. There are eleven values: 0,1,2,3,4,5,6,7,8,9,X. the value is calculated by the fixed formula according to the previous 17 bits.

The 18th digit is calculated according to ISO 7064:1983.MOD 11-2 check code algorithm

// The function parameter must be a string, because the second generation ID card number is 18 bits, and in javascript, the value of 18 bits will exceed the calculation range, resulting in inaccurate results, resulting in inconsistency between the last two bits and the calculated value, resulting in an error in the function.
// See the value range of javascript for details
function checkIDCard(idcode){
    // Weighting factor
    var weight_factor = [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2];
    // Check code
    var check_code = ['1', '0', 'X' , '9', '8', '7', '6', '5', '4', '3', '2'];

    var code = idcode + "";
    var last = idcode[17];//The last one

    var seventeen = code.substring(0,17);

    // ISO 7064:1983.MOD 11-2
    // Judge whether the last check code is correct
    var arr = seventeen.split("");
    var len = arr.length;
    var num = 0;
    for(var i = 0; i < len; i++){
        num = num + arr[i] * weight_factor[i];
    }
    
    // Get remainder
    var resisue = num%11;
    var last_no = check_code[resisue];

    // Regularity of format
    // Regular thinking
    /*
    First place can't be 0
    Second to sixth can be 0-9
    Seventh to tenth are years, so seven or eight are 19 or 20
    The 11th and 12th digits are the month, and these two digits are the values between 01-12
    The 13th and 14th digits are dates, which are values from 01 to 31
    Fifteen, sixteen, seventeen are numbers 0-9
    Eighteen digits can be numbers 0-9, or X
    */
    var idcard_patter = /^[1-9][0-9]{5}([1][9][0-9]{2}|[2][0][0|1][0-9])([0][1-9]|[1][0|1|2])([0][1-9]|[1|2][0-9]|[3][0|1])[0-9]{3}([0-9]|[X])$/;

    // Determine whether the format is correct
    var format = idcard_patter.test(idcode);

    // Return the verification result. Only when the verification code and format are correct at the same time can it be regarded as a legal ID number
    return last === last_no && format ? true : false;
}

Tags: Javascript

Posted on Fri, 08 Nov 2019 11:45:35 -0800 by MikeL7