JavaScript validation for ID card number

Question

Answers ( 1 )

    0
    2024-01-18T16:58:27+00:00

    It's about implementing a method to validate ID card numbers using JavaScript.

    In China, the ID card number is a structured string that contains information like the region, birthdate, and a sequence code. The last digit is a checksum. To validate an ID card number using JavaScript, you typically need to check:

    1. Length and Format: The standard ID card number should be 18 digits long (older cards were 15 digits, but they are less common now).

    2. Birthday Validity: Digits 7-14 represent the birthdate in the format YYYYMMDD.

    3. Checksum: The last digit of the ID card is a checksum calculated using the first 17 digits.

    Here's a basic example in JavaScript to validate an 18-digit ID card number:

    function isValidChineseId(id) {
        if (!/^\d{17}(\d|x)$/i.test(id)) return false; // Check format
    
        // Constants for checksum calculation
        const factors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
        const checksums = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
    
        // Extract birthdate and verify
        const birthdate = id.substring(6, 14);
        if (!/^\d{8}$/.test(birthdate)) return false;
        const year = parseInt(birthdate.substring(0, 4), 10);
        const month = parseInt(birthdate.substring(4, 6), 10) - 1;
        const day = parseInt(birthdate.substring(6, 8), 10);
        const birthday = new Date(year, month, day);
        if (birthday.getFullYear() !== year || birthday.getMonth() !== month || birthday.getDate() !== day) {
            return false;
        }
    
        // Calculate and verify checksum
        let sum = 0;
        for (let i = 0; i < 17; i++) {
            sum += id[i] * factors[i];
        }
        const calculatedChecksum = checksums[sum % 11];
        return id[17].toUpperCase() === calculatedChecksum;
    }
    
    // Example usage
    console.log(isValidChineseId("your_id_number_here")); // Replace with actual ID number
    

    This function does the following:

    • Validates the basic format using a regular expression.
    • Checks if the birthdate is valid.
    • Calculates the checksum and compares it with the last character.

    Remember that this is a basic validation. In real-world applications, you might also need to validate the region code and consider historical changes in ID card formats.

Leave an answer