Guide · Identity

How to validate a Mexican CURP: regex, birth date and check digit in Python, JavaScript and Go

Offline CURP validation: a regex true to the official rules, the real date and the check digit algorithm, with tested code in Python, JavaScript and Go.

OrigoID team Published on 10 min read Leer en español
In this guide
  1. What is inside a CURP
  2. The regex, piece by piece
  3. The birth date
  4. The check digit
  5. The code
  6. Test vectors
  7. What a valid structure does not tell you
  8. Sources

A CURP (Clave Única de Registro de Población) is the 18-character ID that RENAPO, Mexico's population registry, assigns to every citizen and resident. If your signup form, payroll import or onboarding flow takes one, you can check three things without calling anyone:

  1. The shape. Each position only admits certain characters.
  2. The birth date inside it is a real calendar date.
  3. The check digit in the last position matches the other 17 characters.

What you cannot check offline is whether the CURP exists or who it belongs to. More on that at the end.

If you only came for the regex, here it is:

^[A-Z][AEIOUX][A-Z]{2}[0-9]{6}[HMX](?:AS|BC|BS|CC|CH|CL|CM|CS|DF|DG|GR|GT|HG|JC|MC|MN|MS|NE|NL|NT|OC|PL|QR|QT|SL|SP|SR|TC|TL|TS|VZ|YN|ZS)[B-DF-HJ-NP-TV-Z]{3}[0-9A-J][0-9]$

It is stricter than most of the ones that get copy-pasted around, and looser in one place where they are wrong. The rest of the article explains each piece, adds the date and the check digit, and ends with tested code in Python, JavaScript and Go.

What is inside a CURP

The layout comes from the Instructivo Normativo para la asignación de la CURP, published in Mexico's official gazette (DOF) in 2018. Its own example is a woman named Concepción Salgado Briseño, born on 26 June 1956 in the Distrito Federal:

SABC 560626 M DF LRN 0 1
Position What it holds In the example
1 First letter of the first surname S (Salgado)
2 First internal vowel of the first surname A
3 First letter of the second surname B (Briseño)
4 First letter of the given name C (Concepción)
5-10 Birth date as YYMMDD 560626
11 Sex M (mujer)
12-13 State of birth DF
14-16 First internal consonant of the first surname, the second surname and the given name L, R, N
17 Differentiator for people who share the first 16 characters. It also tells you the century 0
18 Check digit 1

One warning about that example. The Instructivo prints the key as SABC560626MDFLRN09, and with the check digit algorithm described below the last digit comes out as 1, not 9. Treat the printed key as a picture of the layout and do not use it as a test case.

The regex, piece by piece

Normalize first. Trim the input and upper-case it before matching, and store the normalized value.

Positions 1-4: [A-Z][AEIOUX][A-Z]{2}. Position 2 is a vowel or an X. The X is the wildcard of the whole system. RENAPO's rules for assigning the CURP (2021) list the cases, with examples:

So a CURP never contains an Ñ, and an X can show up almost anywhere.

Positions 5-10: [0-9]{6}. Only the format at this stage. Write [0-9], not \d. In Python, \d on a str matches any Unicode digit, so full-width digits like 04 pass the regex, and int("04") happily returns 4. In JavaScript and Go \d is ASCII-only, but an explicit class behaves the same everywhere.

Position 11: [HMX]. H is hombre (male) and M is mujer (female). The table in the Instructivo stops there, and so do most regexes. But RENAPO has issued CURPs with an X in this position for non-binary people, following court rulings. An INE report from January 2023 records it: the X goes «en lugar de la “H” o “M”» (in place of the H or M). A validator with [HM] rejects those people.

Positions 12-13: the state. Thirty-two states plus NE (nacido en el extranjero) for people born abroad:

AS Aguascalientes, BC Baja California, BS Baja California Sur, CC Campeche, CH Chihuahua, CL Coahuila, CM Colima, CS Chiapas, DF Ciudad de México, DG Durango, GR Guerrero, GT Guanajuato, HG Hidalgo, JC Jalisco, MC Estado de México, MN Michoacán, MS Morelos, NL Nuevo León, NT Nayarit, OC Oaxaca, PL Puebla, QR Quintana Roo, QT Querétaro, SL Sinaloa, SP San Luis Potosí, SR Sonora, TC Tabasco, TL Tlaxcala, TS Tamaulipas, VZ Veracruz, YN Yucatán, ZS Zacatecas.

The official catalog is Annex 3 of RENAPO's rules, and the published PDF lists the annex without including it. The codes above are the ones in general use.

Positions 14-16: [B-DF-HJ-NP-TV-Z]{3}. Three consonants. X is in the class, and it is used here too: when a name has no internal consonant, when that consonant is an Ñ, and in position 15 when there is only one surname.

Position 17: [0-9A-J]. RENAPO assigns it to tell apart two people whose first 16 characters are identical. Both official documents give the same range: 0-9 for people born up to 31 December 1999 and A-J for people born from 1 January 2000. Many regexes use [0-9A-Z] here.

Position 18: [0-9]. The check digit.

Anchors. In Python use fullmatch. With re.match and $, a trailing newline still matches: re.match(r"^[0-9]{2}$", "04\n") succeeds.

About the offensive-word rule: this validator does not reject a CURP for starting with one of those words, because the official catalog (Annex 1 of the same rules) is not in the published PDF, and rejecting a genuine key is worse than letting a malformed one reach the next check.

The birth date

Six digits with a two-digit year. Position 17 resolves the century: a digit means 19xx and a letter means 20xx. Then build the date and make sure it exists.

Leap years make good test cases:

Two things to watch:

The check digit

Neither the Instructivo nor RENAPO's rules print the algorithm. They only say that position 18 is assigned by an algorithm. The one below is the one in general use. Run it on your own CURP.

  1. Give each character a value: its index in 0123456789ABCDEFGHIJKLMNÑOPQRSTUVWXYZ. That is 37 symbols, with the Ñ between N and O.
  2. Multiply the first 17 values by the weights 18, 17, 16 ... 2, from left to right.
  3. Add everything up.
  4. The digit is (10 - sum % 10) % 10.

For SABC560626MDFLRN0:

Char S A B C 5 6 0 6 2 6 M D F L R N 0
Value 29 10 11 12 5 6 0 6 2 6 22 13 15 21 28 23 0
Weight 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2
Product 522 170 176 180 70 78 0 66 20 54 176 91 90 105 112 69 0

The sum is 1979. 1979 % 10 is 9, and (10 - 9) % 10 is 1.

Three things about this algorithm:

The code

Each version returns which of the three checks failed, so you can show a useful message.

"""Structural validation of a Mexican CURP: format, real birth date, check digit.

This does not tell you whether the CURP exists in RENAPO's registry.
"""
import re
from datetime import date

STATES = (
    "AS|BC|BS|CC|CH|CL|CM|CS|DF|DG|GR|GT|HG|JC|MC|MN|MS|NE|NL|NT|OC|"
    "PL|QR|QT|SL|SP|SR|TC|TL|TS|VZ|YN|ZS"
)

CURP_RE = re.compile(
    r"[A-Z][AEIOUX][A-Z]{2}"          # 1-4   letters taken from the names
    r"([0-9]{2})([0-9]{2})([0-9]{2})"  # 5-10  birth date, YYMMDD
    r"[HMX]"                           # 11    sex
    rf"(?:{STATES})"                   # 12-13 state of birth, NE = born abroad
    r"[B-DF-HJ-NP-TV-Z]{3}"            # 14-16 internal consonants
    r"([0-9A-J])"                      # 17    homonym / century differentiator
    r"([0-9])"                         # 18    check digit
)

# 37 symbols: the Ñ sits between N and O even though it never appears in a CURP.
ALPHABET = "0123456789ABCDEFGHIJKLMNÑOPQRSTUVWXYZ"


def check_digit(curp17: str) -> int:
    """Check digit for the first 17 characters of a CURP."""
    total = sum(ALPHABET.index(c) * (18 - i) for i, c in enumerate(curp17[:17]))
    return (10 - total % 10) % 10


def validate_curp(value, today=None):
    """Return (True, "ok") or (False, reason).

    reason is one of "format", "date", "check_digit".
    """
    if not isinstance(value, str):
        return False, "format"
    curp = value.strip().upper()

    m = CURP_RE.fullmatch(curp)
    if not m:
        return False, "format"
    yy, mm, dd, differentiator, digit = m.groups()

    # Position 17 carries the century: 0-9 = born up to 1999, A-J = 2000 onwards.
    century = 1900 if differentiator.isdigit() else 2000
    try:
        born = date(century + int(yy), int(mm), int(dd))
    except ValueError:
        return False, "date"
    if born > (today or date.today()):
        return False, "date"

    if check_digit(curp) != int(digit):
        return False, "check_digit"
    return True, "ok"
// Structural validation of a Mexican CURP: format, real birth date, check digit.
// This does not tell you whether the CURP exists in RENAPO's registry.

const STATES =
  "AS|BC|BS|CC|CH|CL|CM|CS|DF|DG|GR|GT|HG|JC|MC|MN|MS|NE|NL|NT|OC|" +
  "PL|QR|QT|SL|SP|SR|TC|TL|TS|VZ|YN|ZS";

const CURP_RE = new RegExp(
  "^[A-Z][AEIOUX][A-Z]{2}" +           // 1-4   letters taken from the names
    "([0-9]{2})([0-9]{2})([0-9]{2})" + // 5-10  birth date, YYMMDD
    "[HMX]" +                          // 11    sex
    `(?:${STATES})` +                  // 12-13 state of birth, NE = born abroad
    "[B-DF-HJ-NP-TV-Z]{3}" +           // 14-16 internal consonants
    "([0-9A-J])" +                     // 17    homonym / century differentiator
    "([0-9])$"                         // 18    check digit
);

// 37 symbols: the Ñ sits between N and O even though it never appears in a CURP.
const ALPHABET = "0123456789ABCDEFGHIJKLMNÑOPQRSTUVWXYZ";

/** Check digit for the first 17 characters of a CURP. */
export function checkDigit(curp17) {
  let total = 0;
  for (let i = 0; i < 17; i++) {
    total += ALPHABET.indexOf(curp17[i]) * (18 - i);
  }
  return (10 - (total % 10)) % 10;
}

/** Returns { ok: true } or { ok: false, reason: "format" | "date" | "check_digit" }. */
export function validateCurp(value, today = new Date()) {
  if (typeof value !== "string") return { ok: false, reason: "format" };
  const curp = value.trim().toUpperCase();

  const m = CURP_RE.exec(curp);
  if (!m) return { ok: false, reason: "format" };
  const [, yy, mm, dd, differentiator, digit] = m;

  // Position 17 carries the century: 0-9 = born up to 1999, A-J = 2000 onwards.
  const century = differentiator <= "9" ? 1900 : 2000;
  const year = century + Number(yy);
  const month = Number(mm);
  const day = Number(dd);
  // Date rolls invalid dates over (Feb 30 becomes Mar 2), so read it back.
  const born = new Date(Date.UTC(year, month - 1, day));
  if (born.getUTCMonth() !== month - 1 || born.getUTCDate() !== day) {
    return { ok: false, reason: "date" };
  }
  if (born.getTime() > today.getTime()) return { ok: false, reason: "date" };

  if (checkDigit(curp) !== Number(digit)) {
    return { ok: false, reason: "check_digit" };
  }
  return { ok: true };
}
// Package curp validates the structure of a Mexican CURP: format, real birth
// date and check digit. It does not tell you whether the CURP exists in
// RENAPO's registry.
package curp

import (
	"errors"
	"regexp"
	"strconv"
	"strings"
	"time"
)

var (
	ErrFormat     = errors.New("curp: invalid format")
	ErrDate       = errors.New("curp: invalid birth date")
	ErrCheckDigit = errors.New("curp: check digit mismatch")
)

const states = "AS|BC|BS|CC|CH|CL|CM|CS|DF|DG|GR|GT|HG|JC|MC|MN|MS|NE|NL|NT|OC|" +
	"PL|QR|QT|SL|SP|SR|TC|TL|TS|VZ|YN|ZS"

var curpRe = regexp.MustCompile(
	`^[A-Z][AEIOUX][A-Z]{2}` + // 1-4   letters taken from the names
		`([0-9]{2})([0-9]{2})([0-9]{2})` + // 5-10  birth date, YYMMDD
		`[HMX]` + // 11    sex
		`(?:` + states + `)` + // 12-13 state of birth, NE = born abroad
		`[B-DF-HJ-NP-TV-Z]{3}` + // 14-16 internal consonants
		`([0-9A-J])` + // 17    homonym / century differentiator
		`([0-9])$`, // 18    check digit
)

// charValue is the position of c in "0123456789ABCDEFGHIJKLMNÑOPQRSTUVWXYZ".
// It is computed instead of looked up because Ñ takes two bytes in UTF-8, so
// strings.IndexByte on that literal would be off by one from O onwards.
func charValue(c byte) int {
	switch {
	case c >= '0' && c <= '9':
		return int(c - '0')
	case c >= 'A' && c <= 'N':
		return int(c-'A') + 10
	default: // O-Z, after the slot that belongs to Ñ
		return int(c-'A') + 11
	}
}

// CheckDigit returns the check digit for the first 17 characters of a CURP.
func CheckDigit(curp17 string) int {
	total := 0
	for i := 0; i < 17; i++ {
		total += charValue(curp17[i]) * (18 - i)
	}
	return (10 - total%10) % 10
}

// Validate returns nil when value is a structurally valid CURP, or one of
// ErrFormat, ErrDate, ErrCheckDigit.
func Validate(value string) error {
	return validateAt(value, time.Now())
}

func validateAt(value string, today time.Time) error {
	curp := strings.ToUpper(strings.TrimSpace(value))

	m := curpRe.FindStringSubmatch(curp)
	if m == nil {
		return ErrFormat
	}
	yy, _ := strconv.Atoi(m[1])
	mm, _ := strconv.Atoi(m[2])
	dd, _ := strconv.Atoi(m[3])
	differentiator, digit := m[4][0], int(m[5][0]-'0')

	// Position 17 carries the century: 0-9 = born up to 1999, A-J = 2000 onwards.
	century := 2000
	if differentiator <= '9' {
		century = 1900
	}
	// time.Date rolls invalid dates over (Feb 30 becomes Mar 2), so read it back.
	born := time.Date(century+yy, time.Month(mm), dd, 0, 0, 0, 0, time.UTC)
	if int(born.Month()) != mm || born.Day() != dd {
		return ErrDate
	}
	if born.After(today) {
		return ErrDate
	}

	if CheckDigit(curp) != digit {
		return ErrCheckDigit
	}
	return nil
}

Test vectors

Use these to test your own port. The SABC ones derive from the example in the Instructivo; the rest are sample keys.

Input Result Why
BOXW310820HNERXN09 ok Born abroad (NE)
SABC560626MDFLRN01 ok The Instructivo's example with the digit the algorithm gives
SABC560626MDFLRN09 check digit The same key as printed
WUKQ040229HNEQWKA1 ok 29 Feb 2004
WUKQ000229HNEQWKA3 ok 29 Feb 2000
WUKQ000229HNEQWK03 date 29 Feb 1900 does not exist
WUKQ990431HNEQWK00 date 31 April
SABC560626MDFLRNA1 date Letter in position 17 means 2056
SABC560626XDFLRN05 ok X as sex
PXDO850714MOCDMF00 ok X in position 2
ZAXM750301MSLRXR08 ok Single surname
XXXJ800101HNEXXN03 ok No surnames
WUKQ040229HNEQWKK1 format K is outside A-J
WUKQ040229ZNEQWKA1 format Sex is not H, M or X
WUKQ040229HNEQWKA1 format Full-width digits

How this was tested: 36 vectors run against the three implementations, and 200,000 random inputs (valid keys, wrong digits, impossible dates, stray characters) gave the same verdict in all three.

What a valid structure does not tell you

A key that passes all three checks is well formed. That is all. It can still be a CURP that was never assigned, one that belongs to somebody else, or one that RENAPO has since deactivated. Only the registry can answer that, and that is what our API to validate a CURP against RENAPO does.

Offline validation is still worth having as the first step: it rejects typos and junk before you spend a lookup on them, and it lets you tell the user which part is wrong.

Rebuilding the first four letters from a person's name is possible too, but the rules are long: compound names, María and José, particles such as DE LA. They are all in RENAPO's rules, linked below.

Sources

Related services

Keep reading

All guides ›
Identity CURP, RFC, NSS and INE: Mexico's IDs explained

Mexico's CURP, RFC, NSS and INE are not interchangeable: who assigns each one, who has it, what is inside and what you can validate offline.

7 min
For developers Mexican identity verification with MCP

From zero to a service that validates Mexico's CURP with OrigoID's API using its MCP server in Claude Code, and the design choices that make it fast.

5 min
Compliance Mexico's UIF blocked persons list: what to check

Mexico's UIF blocked persons list is confidential and has no public lookup. Its seven legal grounds and the public lists you can screen instead.

6 min
Start free, no card.

Courtesy credits to try it with your own data. Access is enabled after a brief validation of your company.

Request access