Disclosure: I'm Adrian Rangel, the founder of MexCheck, which I mention near the end. The first two thirds of this post are plain Python with no dependencies, and you can use them without signing up for anything. All identifiers below are public examples, not real people.

If your company onboards Mexican customers, contractors or suppliers, sooner or later a form asks for an RFC (the SAT tax ID) or a CURP (the national population ID). Payroll needs both, CFDI invoicing needs the RFC, and KYC usually wants the CURP.

A regex copied from somewhere catches some typos, but lets through wrong check digits, impossible dates, and IDs that are well formed but belong to nobody. Here are the real formats, a tested validator, and where offline validation stops being enough.

The RFC: 13 characters for people, 12 for companies

Part Persona fisica (individual) Persona moral (company)
Letters 4, from surnames and first name 3, from the company name
Date YYMMDD birth date YYMMDD incorporation date
Homoclave 2 characters assigned by SAT 2 characters assigned by SAT
Check digit 0-9 or A 0-9 or A
Length 13 12

So GODE561231GR8 (the example in SAT's own instructions) is an individual born 1956-12-31, and SAT970701NN3 is a company incorporated 1997-07-01.

Gotchas:

  • Ñ and & are legal letters. A company called "P&G Something" gets an & in its RFC, and surnames like Muñoz give you an Ñ. A [A-Z] regex rejects valid taxpayers. Make sure your column and your form are UTF-8.
  • The homoclave is not derivable in practice. There is a published procedure, but SAT assigns it and resolves homonyms on its side. Do not try to regenerate an RFC from the person's name and compare; take what is on their Constancia de Situacion Fiscal.
  • Inconvenient words. When the four initials spell an offensive word, the authority replaces a letter with X. Another reason not to rebuild the ID from the name.
  • Generic RFCs. XAXX010101000 (domestic counterpart without an RFC, used for "publico en general" invoices) and XEXX010101000 (foreign counterpart) do not follow the check-digit algorithm. Treat them as a separate case, not as valid customer IDs.

The RFC check digit (mod 11)

Each of the first 12 characters maps to a value in the table 0123456789ABCDEFGHIJKLMN&OPQRSTUVWXYZ Ñ (so & = 24, space = 37, Ñ = 38). Company RFCs are padded with a leading space to 12 characters. Multiply by weights 13 down to 2, sum, and take 11 - (sum % 11); 11 becomes 0 and 10 becomes A.

The CURP: 18 characters

PEMJ800101HDFRRN07 breaks down as:

  • PEMJ: first surname initial + its first internal vowel, second surname initial, first name initial. When these spell an inconvenient word, RENAPO replaces the second character with X, so position 2 is a vowel or X. An Ñ in a name is also written as X in the key, which is why the CURP regex below only accepts A-Z.
  • 800101: birth date YYMMDD.
  • H: sex (H, M, or X).
  • DF: state of birth (32 codes, plus NE for born abroad).
  • RRN: first internal consonants of each surname and the first name.
  • 0: differentiator assigned by RENAPO to avoid duplicates (in practice, a digit for people born before 2000 and a letter after).
  • 7: check digit.

The CURP check digit (mod 10)

Map the first 17 characters with 0123456789ABCDEFGHIJKLMNÑOPQRSTUVWXYZ (a different table from the RFC one: Ñ sits right after N at value 24, and there is no & or space), multiply by weights 18 down to 2, sum, and the digit is (10 - sum % 10) % 10.

A tested validator

Save this as mxid.py. Standard library only.

import re from datetime import date # --- RFC ------------------------------------------------------------- RFC_RE = re.compile( r"^(?P<letters>[A-ZÑ&]{3,4})" # 3 letters (company) or 4 (person) r"(?P<date>\d{6})" # YYMMDD r"(?P<homoclave>[A-Z\d]{2})" # assigned by SAT r"(?P<check>[A\d])$" # check digit: 0-9 or A ) # SAT value table (0..38): '&' = 24, ' ' = 37, 'Ñ' = 38 RFC_CHARS = "0123456789ABCDEFGHIJKLMN&OPQRSTUVWXYZ Ñ" GENERIC_RFCS = {"XAXX010101000", "XEXX010101000"} def _valid_yymmdd(s: str) -> bool: # The century is unknown; 2000 is a leap year, so 29 Feb always passes. try: date(2000 + int(s[:2]), int(s[2:4]), int(s[4:6])) return True except ValueError: return False def rfc_check_digit(rfc: str) -> str: base = rfc[:-1] if len(base) == 11: # company RFC: pad to 12 with a leading space base = " " + base total = sum(RFC_CHARS.index(c) * (13 - i) for i, c in enumerate(base)) d = 11 - total % 11 return "0" if d == 11 else "A" if d == 10 else str(d) def validate_rfc(value: str) -> str: rfc = value.strip().upper() m = RFC_RE.match(rfc) if not m or not _valid_yymmdd(m["date"]): return "bad_format" if rfc in GENERIC_RFCS: return "generic" if rfc_check_digit(rfc) != m["check"]: return "bad_check_digit" return "ok" # --- CURP ------------------------------------------------------------ STATES = ("AS|BC|BS|CC|CL|CM|CS|CH|DF|DG|GT|GR|HG|JC|MC|MN|MS|NT|NL|OC|PL" "|QT|QR|SP|SL|SR|TC|TS|TL|VZ|YN|ZS|NE") CURP_RE = re.compile( r"^[A-Z][AEIOUX][A-Z]{2}" # surname/name initials r"(?P<date>\d{6})" # YYMMDD r"[HMX]" # sex rf"(?:{STATES})" # state of birth (NE = born abroad) r"[B-DF-HJ-NP-TV-Z]{3}" # internal consonants r"[A-Z\d]" # differentiator r"(?P<check>\d)$" # check digit ) CURP_CHARS = "0123456789ABCDEFGHIJKLMNÑOPQRSTUVWXYZ" def curp_check_digit(curp: str) -> str: total = sum(CURP_CHARS.index(c) * (18 - i) for i, c in enumerate(curp[:17])) return str((10 - total % 10) % 10) def validate_curp(value: str) -> str: curp = value.strip().upper() m = CURP_RE.match(curp) if not m or not _valid_yymmdd(m["date"]): return "bad_format" if curp_check_digit(curp) != m["check"]: return "bad_check_digit" return "ok" 

Two design choices worth copying:

  1. It returns a reason, not a boolean. bad_format is a typo you can show inline in the form. bad_check_digit on an RFC is better treated as "ask SAT" than as a hard reject: the registry, not the algorithm, is the source of truth, and the cost of a false rejection at onboarding is a lost customer.
  2. It validates the date with datetime, which a regex like (0[1-9]|[12]\d|3[01]) cannot do: it happily accepts 31 February.

Running it:

from mxid import validate_rfc, validate_curp for rfc in ["GODE561231GR8", # person, 13 chars (SAT's own example) "SAT970701NN3", # company, 12 chars "gode561231gr8 ", # lowercase + stray whitespace "GODE561231GR9", # wrong check digit "GODE560231GR8", # 31 February "XAXX010101000"]: # SAT generic RFC print(f"{rfc!r:18} {validate_rfc(rfc)}") for curp in ["PEMJ800101HDFRRN07", # documentation example "PEMJ800101HDFRRN08", # wrong check digit "PEMJ800101HZZRRN07", # ZZ is not a state code "PEMJ800230HDFRRN07"]: # 30 February print(f"{curp!r:22} {validate_curp(curp)}") 

Output (Python 3, run as-is):

'GODE561231GR8' ok 'SAT970701NN3' ok 'gode561231gr8 ' ok 'GODE561231GR9' bad_check_digit 'GODE560231GR8' bad_format 'XAXX010101000' generic 'PEMJ800101HDFRRN07' ok 'PEMJ800101HDFRRN08' bad_check_digit 'PEMJ800101HZZRRN07' bad_format 'PEMJ800230HDFRRN07' bad_format 

Why format + checksum is not enough

Everything above runs offline and catches typos. It cannot tell you any of the things compliance actually cares about:

  • Is the RFC registered and active with SAT? A well-formed RFC with a correct check digit can belong to nobody. For CFDI 4.0 invoicing, the receiver's RFC, name and postal code must also match SAT's record, or stamping fails.
  • Is the supplier on a SAT blacklist? SAT publishes taxpayers under Article 69 (non-compliant, cancelled, etc.), Article 69-B (issuers of simulated invoices, the "EFOS" list) and 69-B Bis. Paying an EFOS can cost you the deduction.
  • Does the CURP exist in RENAPO, and does it belong to this person? For KYC you want to compare RENAPO's names and birth date against what the user typed.
  • Is that invoice still valid? A CFDI can be cancelled after you receive it; only SAT's Verifica CFDI service says whether it is vigente or cancelado.

The government offers no simple JSON API for these. The portals are HTML forms, some with CAPTCHAs, and they go down. You can scrape them yourself or use a service that does.

A live lookup with the MexCheck API

This is the part where I talk about my own product. MexCheck wraps SAT, RENAPO and other registries behind one REST API. Base URL https://mexcheck.com/v1, every endpoint is POST with JSON, and the key goes in the x-api-key header. Keep it in an environment variable:

export MEXCHECK_API_KEY="your_key_here" 

The client below uses the validator above as a free pre-filter, then calls three documented endpoints: /rfc/verify (is the RFC registered with SAT), /rfc/sat-lists (Article 69 / 69-B / 69-B Bis) and /curp/lookup (RENAPO).

import os import requests from mxid import validate_rfc, validate_curp API = "https://mexcheck.com/v1" session = requests.Session() session.headers["x-api-key"] = os.environ["MEXCHECK_API_KEY"] def mexcheck(path: str, body: dict) -> dict: # Lookups wait on SAT/RENAPO and can take up to 90 s. # If you hang up first, the lookup is cancelled and not charged. r = session.post(f"{API}{path}", json=body, timeout=95) if r.status_code == 402: raise RuntimeError(f"Out of credits: {r.json().get('add_balance_url')}") if r.status_code == 422: raise ValueError(f"Rejected input: {r.json().get('error')}") r.raise_for_status() return r.json() def check_supplier(rfc: str) -> dict: if validate_rfc(rfc) == "bad_format": return {"ok": False, "reason": "typo"} # free, no API call verify = mexcheck("/rfc/verify", {"rfc": rfc}) if verify["valid"] is None: return {"ok": None, "reason": "SAT unreachable, retry"} lists = mexcheck("/rfc/sat-lists", {"rfc": rfc}) return { "ok": verify["valid"] and not lists["sat_lists"], "sat_message": verify["message"], "sat_lists": [(e["article"], e["situation"]) for e in lists["sat_lists"]], } def check_person(curp: str) -> dict: if validate_curp(curp) != "ok": return {"ok": False, "reason": "typo"} data = mexcheck("/curp/lookup", {"curp": curp}) if data["found"] is None: return {"ok": None, "reason": "RENAPO unreachable, retry (not charged)"} if not data["found"]: return {"ok": False, "reason": data["message"]} p = data["person"] return {"ok": True, "names": p["names"], "paternal_surname": p["paternal_surname"], "mothers_maiden_name": p["mothers_maiden_name"], "birthdate": p["birthdate"]} 

What the documented responses mean:

  • /rfc/verify returns rfc, valid and message. valid is true, false, or null when SAT could not be reached (retry). For the generic RFCs it also returns generic: true without querying SAT. Add name and zip (always together) to check the full CFDI 4.0 combination.
  • /rfc/sat-lists returns a sat_lists array; each entry has article, sub_list, situation, name, person_type and state. An empty list means the RFC is on none of them.
  • /curp/lookup returns found (true / false / null) and a person object with names, paternal_surname, mothers_maiden_name, birthdate (DD/MM/YYYY), status_curp and more. null means RENAPO was unreachable and is not charged. A CURP that fails format or check digit is rejected with 422 invalid_curp before RENAPO is called, also not charged.
  • Set the client timeout to at least 90 seconds. Lookups wait on government sites; a 504 with {"error": "request_timeout"} is not charged.

For invoices there is /cfdi/verify, which takes uuid, rfc_emisor and rfc_receptor (or the XML itself) and returns status as vigente or cancelado.

Using it from an AI coding assistant (MCP)

There is also a remote MCP server at https://mexcheck.com/mcp (Streamable HTTP, OAuth 2.1 with dynamic client registration and PKCE). It is for building the integration: the assistant reads the docs, pulls each endpoint's OpenAPI definition, and runs real checks. Production code still calls the REST API with a key.

Claude Code:

claude mcp add --transport http mexcheck https://mexcheck.com/mcp 

Cursor (.cursor/mcp.json):

{ "mcpServers": { "mexcheck": { "url": "https://mexcheck.com/mcp" } } } 

There is no key to paste. The docs tools (list_docs, read_doc, get_openapi_operation) work without logging in; the first time the assistant uses a tool that touches your account (like rfc_verify or curp_lookup), it opens a browser for you to sign in. Those checks are real and cost the same as REST calls, and the returned personal data passes through whatever assistant you connected, so only connect one you trust with it.

Pricing

From the pricing page at the time of writing: pay as you go at $0.015 USD per credit with a $5 USD signup bonus, or monthly plans from $99 USD/month (Basic, 10,000 credits). /rfc/verify costs 1 credit, /curp/lookup 5, /cfdi/verify 5, and /rfc/sat-lists is free on any plan (1 credit on pay as you go).

Summary

  1. Validate format, date and check digit locally. It is free and catches most typos.
  2. Return reasons, not booleans; do not hard-reject an RFC only on its check digit.
  3. Handle Ñ, &, generic RFCs and the X substitution rule.
  4. For anything compliance-related (registration, blacklists, identity, invoice status), ask the registry, whether you scrape it yourself or use an API.

There is a Spanish version of this topic with curl and Node.js examples here. Found an RFC or CURP edge case this validator gets wrong? Tell me in the comments.