Download Cheat sheet PDF 12 pages · syntax, editors, patterns, Unicode, performance, debugging
Blog

How to validate an Aadhaar number with regex (Python)

Validating Indian Aadhaar numbers takes two steps — a regex for format, then a Verhoeff checksum for actual validity. Here's how to do both in Python.

Aadhaar numbers are 12 digits, with the first digit between 2 and 9 (UIDAI specs disallow 0 and 1). The regex part is simple:

import re

AADHAAR_RE = re.compile(r"^[2-9]\d{11}$")

def is_aadhaar_format(s):
    return bool(AADHAAR_RE.match(s))

This catches malformed input cheaply, but ~10 billion 12-digit numbers look valid by format alone. For true validation, run the Verhoeff checksum.

The Verhoeff algorithm

d_table = [
    [0,1,2,3,4,5,6,7,8,9], [1,2,3,4,0,6,7,8,9,5],
    [2,3,4,0,1,7,8,9,5,6], [3,4,0,1,2,8,9,5,6,7],
    [4,0,1,2,3,9,5,6,7,8], [5,9,8,7,6,0,4,3,2,1],
    [6,5,9,8,7,1,0,4,3,2], [7,6,5,9,8,2,1,0,4,3],
    [8,7,6,5,9,3,2,1,0,4], [9,8,7,6,5,4,3,2,1,0],
]
p_table = [
    [0,1,2,3,4,5,6,7,8,9], [1,5,7,6,2,8,3,0,9,4],
    [5,8,0,3,7,9,6,1,4,2], [8,9,1,6,0,4,3,5,2,7],
    [9,4,5,3,1,2,6,8,7,0], [4,2,8,6,5,7,3,9,0,1],
    [2,7,9,3,8,0,6,4,1,5], [7,0,4,6,9,1,3,2,5,8],
]

def verhoeff_valid(num):
    c = 0
    for i, digit in enumerate(reversed(num)):
        c = d_table[c][p_table[i % 8][int(digit)]]
    return c == 0

def is_valid_aadhaar(s):
    return is_aadhaar_format(s) and verhoeff_valid(s)

Test it

print(is_valid_aadhaar("234567890123"))  # Format-valid only; True if checksum passes
print(is_valid_aadhaar("123456789012"))  # False — starts with 1

Use this for client-side / server-side sanity checking before submitting to UIDAI APIs. Never store raw Aadhaar in your database without proper compliance — UIDAI requires hashing and encryption.

Try the regex in the Aadhaar pattern page or paste it into the explainer.


← Back to blog