RT

Code Snippet: Validate Routing Numbers in Python

The following code snippet can be used to check if an ABA routing number is potentially valid.

def valid_routing_number(routing_number: str) -> bool:
    if len(routing_number) != 9:
        # Routing numbers are always 9 digits
        return False

    if not routing_number.isnumeric():
        # Routing numbers are always numeric
        return False

    # Calculate checksum
    checksum = (3 * (int(routing_number[0]) + int(routing_number[3]) + int(routing_number[6]))) + \
               (7 * (int(routing_number[1]) + int(routing_number[4]) + int(routing_number[7]))) + \
               (1 * (int(routing_number[2]) + int(routing_number[5]) + int(routing_number[8])))

    # If the checksum is a multiple of 10, the number is potentially valid
    return (checksum % 10) == 0

Note: The function doesn’t check if the routing number is actually assigned to a bank. You can delegate the extra validation to your payment processor or maintain a list of valid routing numbers on your end.