Python code for validation of NRIC

import re

def validate_nric(number):
    # Remove all non-alphanumeric characters from the input
    number = re.sub(r'[^a-zA-Z0-9]', '', number)
    
    # Check if the input is a valid NRIC number
    if re.match(r'^[stfgSTFG][0-9]{7}[a-zA-Z]$', number):
        # Check the checksum of the NRIC number
        nric_arr = list(number)
        nric_arr[1] = str(int(nric_arr[1]) * 2)
        nric_arr[2] = str(int(nric_arr[2]) * 7)
        nric_arr[3] = str(int(nric_arr[3]) * 6)
        nric_arr[4] = str(int(nric_arr[4]) * 5)
        nric_arr[5] = str(int(nric_arr[5]) * 4)
        nric_arr[6] = str(int(nric_arr[6]) * 3)
        nric_arr[7] = str(int(nric_arr[7]) * 2)

        weight = sum([int(i) for i in nric_arr])
        offset = 4 if number[0] in ['T', 'G'] else 0
        check_code = 'JZIHGFEDCBA'[11 - ((weight + offset) % 11)]

        return check_code == number[-1].upper()

    else:
        return False

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.