Guide · Tax

How to validate a Mexican RFC: SAT's own regex, the date and the check digit in Python, JavaScript and Go

Offline validation of Mexico's RFC tax ID: the pattern SAT publishes, the date and the check digit, and why a mismatch is not a reason to reject.

OrigoID team Published on 9 min read Leer en español
In this guide
  1. What is inside an RFC
  2. The regex, part by part
  3. The date
  4. The check digit
  5. The check digit is not a reason to reject
  6. The homoclave cannot be verified
  7. The code
  8. Test cases
  9. What a valid structure does not tell you
  10. Sources

The RFC (Registro Federal de Contribuyentes) is the tax ID that SAT, Mexico's tax authority, assigns to every person and company that pays taxes in the country. It goes on every invoice, every supplier record and every payroll. If your system receives one, there are three things you can check without calling anyone:

  1. The shape. Each position only allows certain characters.
  2. The date inside it exists.
  3. The check digit in the last position matches the rest.

The first two are grounds for rejection. The third is not, and that is where almost every validator gets it wrong. What you cannot know offline is whether the RFC exists or whose it is.

If you only came for the regex, this is the one SAT publishes in the schema of its own invoices, with start and end anchors added:

^[A-Z&Ñ]{3,4}[0-9]{2}(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])[A-Z0-9]{2}[0-9A]$

The rest of this article explains each part, adds the date and the check digit, and ends with tested code in Python, JavaScript and Go.

What is inside an RFC

There are two lengths. An individual's RFC has 13 characters; a company's has 12.

Part Individual Company
Letters 4, taken from the surnames and the given name 3, taken from the company name
Date, YYMMDD Birth Incorporation
Homoclave 2 characters 2 characters
Check digit 1 character 1 character

The examples in SAT's document describing the algorithm:

People usually call the last three characters together "the homoclave".

The regex, part by part

Normalize first. People type the RFC with hyphens and spaces (GODE-561231-GR8) and in lower case. Remove spaces and hyphens, upper-case it, and store the normalized value. Two details that almost nobody handles:

The letters: [A-Z&Ñ]{3,4}. Unlike the CURP, an RFC can contain Ñ, and also &, which shows up in company names. Those two characters cause most of the trouble outside validation:

When an individual's four letters spell an offensive word, SAT replaces the last one with an X (BUEI becomes BUEX). The list is in Annex IV of the document. SAT's schema does not check it and neither does this code.

The date: [0-9]{2}(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01]). SAT's regex already rules out month 13 and day 32. Write [0-9], not \d: in Python, \d on a str accepts any Unicode digit, so 56 (full-width digits) gets through.

The homoclave: [A-Z0-9]{2}. Two characters that tell apart taxpayers who share letters and date.

The check digit: [0-9A]. A digit or the letter A.

The date

The regex accepts February 30. You have to build the date and see that it exists.

Here the RFC is worse than the CURP: nothing in it tells you the century. 000229 can be 1900 or 2000. Two consequences:

The check digit

The algorithm comes from a document SAT released in 2006 in response to a freedom-of-information request (file 0610100135506). It works like this.

Each character is worth its position in this 39-symbol table:

0123456789ABCDEFGHIJKLMN&OPQRSTUVWXYZ Ñ

0 to 9 are worth 0 to 9; A to N, 10 to 23; &, 24; O to Z, 25 to 36; the space, 37; Ñ, 38. Then:

  1. Drop the check digit. If 11 characters are left (a company), prepend a space to get 12.
  2. Multiply each character's value by a factor that goes down from 13 to 2, and add everything up.
  3. Take the remainder of dividing the sum by 11.
  4. The digit is 11 minus the remainder. If that gives 11, the digit is 0. If it gives 10, it is A.

With the document's example, GODE561231GR:

16×13 + 25×12 + 13×11 + 14×10 + 5×9 + 6×8 + 1×7 + 2×6 + 3×5 + 1×4 + 16×3 + 28×2 = 1026
1026 mod 11 = 3
11 − 3 = 8

The full RFC is GODE561231GR8.

A warning about step 4. The document literally says "if the remainder equals 10 the check digit will be A". Read that way it does not add up: with remainder 10 the subtraction gives 1, and with remainder 1 it gives 10, which does not fit in one character. What equals 10 is the result of the subtraction, and that is what the code below does.

The check digit is not a reason to reject

This is where most validators fail. There are valid RFCs, in use, whose check digit does not match the algorithm.

The generic RFC. When you invoice someone who did not give you an RFC, rule 2.7.1.23 of Mexico's annual tax rules (Resolución Miscelánea Fiscal) tells you to use XAXX010101000, and XEXX010101000 for a foreign resident. The algorithm says XAXX010101000 should end in 4. If you reject on the check digit, you reject the value SAT orders you to use.

SAT assigns the key, not the algorithm. The document describing the calculation warns that only SAT officially assigns the keys. And the schema of its invoices does not check the digit: it only checks the shape.

That is why the code has two separate functions:

The homoclave cannot be verified

The two homoclave characters come from the full name. SAT's document describes the calculation: each letter of the name gets a value, the values are multiplied in pairs and added up, the last three digits are taken and divided by 34. The quotient and the remainder are looked up in a 34-symbol table that has no 0 and no O.

It is useless for validation, for two reasons:

XAXX010101000 shows it: its homoclave is 00, which the calculation never produces.

The code

The three implementations do the same thing and return the same results.

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

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

# The pattern SAT publishes in its own invoice schema (tdCFDI.xsd, type t_RFC).
RFC_RE = re.compile(
    r"[A-Z&Ñ]{3,4}"                                        # 3 letters = company, 4 = person
    r"([0-9]{2})(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])"   # date, YYMMDD
    r"[A-Z0-9]{2}"                                         # homonym differentiator
    r"[0-9A]"                                              # check digit
)

# 39 symbols. The & sits between N and O; the space pads 12-character RFCs.
ALPHABET = "0123456789ABCDEFGHIJKLMN&OPQRSTUVWXYZ Ñ"

# Placeholders SAT defines for invoices to the general public and to foreigners.
GENERIC = frozenset({"XAXX010101000", "XEXX010101000"})

_UPPER = str.maketrans("abcdefghijklmnopqrstuvwxyzñ", "ABCDEFGHIJKLMNOPQRSTUVWXYZÑ")


def normalize(value: str) -> str:
    """Compose the Ñ, drop spaces and hyphens, upper-case a-z and ñ only."""
    text = value.replace("n\u0303", "ñ").replace("N\u0303", "Ñ")
    return re.sub(r"[ \t\r\n-]", "", text).translate(_UPPER)


def check_digit(body: str) -> str:
    """Check digit for an RFC without its last character (11 or 12 characters)."""
    padded = body.rjust(12)
    total = sum(ALPHABET.index(c) * (13 - i) for i, c in enumerate(padded))
    return ALPHABET[(11 - total % 11) % 11]


def validate_rfc(value):
    """Return (True, "ok") or (False, reason); reason is "format" or "date"."""
    if not isinstance(value, str):
        return False, "format"
    m = RFC_RE.fullmatch(normalize(value))
    if not m:
        return False, "format"
    yy, mm, dd = (int(g) for g in m.groups())
    try:
        date(2000 + yy, mm, dd)  # the century is unknown; 2000 keeps 29 Feb of year 00
    except ValueError:
        return False, "date"
    return True, "ok"


def check_digit_matches(value) -> bool:
    """Soft signal: a real RFC can fail it. False for anything validate_rfc rejects."""
    if not validate_rfc(value)[0]:
        return False
    rfc = normalize(value)
    return check_digit(rfc[:-1]) == rfc[-1]
// Structural validation of a Mexican RFC: format, real date, check digit.
// This does not tell you whether the RFC exists in SAT's registry.

// The pattern SAT publishes in its own invoice schema (tdCFDI.xsd, type t_RFC).
const RFC_RE =
  /^[A-Z&Ñ]{3,4}([0-9]{2})(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])[A-Z0-9]{2}[0-9A]$/;

// 39 symbols. The & sits between N and O; the space pads 12-character RFCs.
const ALPHABET = "0123456789ABCDEFGHIJKLMN&OPQRSTUVWXYZ Ñ";

// Placeholders SAT defines for invoices to the general public and to foreigners.
export const GENERIC = new Set(["XAXX010101000", "XEXX010101000"]);

// Compose the Ñ, drop spaces and hyphens, upper-case a-z and ñ only.
export function normalize(value) {
  return value
    .replace(/n\u0303/g, "ñ")
    .replace(/N\u0303/g, "Ñ")
    .replace(/[ \t\r\n-]/g, "")
    .replace(/[a-zñ]/g, (c) => c.toUpperCase());
}

// Check digit for an RFC without its last character (11 or 12 characters).
export function checkDigit(body) {
  const padded = body.padStart(12, " ");
  let total = 0;
  for (let i = 0; i < 12; i++) {
    total += ALPHABET.indexOf(padded[i]) * (13 - i);
  }
  return ALPHABET[(11 - (total % 11)) % 11];
}

// Returns { ok: true, reason: "ok" } or { ok: false, reason: "format" | "date" }.
export function validateRfc(value) {
  if (typeof value !== "string") return { ok: false, reason: "format" };
  const m = RFC_RE.exec(normalize(value));
  if (!m) return { ok: false, reason: "format" };

  const [yy, mm, dd] = [Number(m[1]), Number(m[2]), Number(m[3])];
  // The century is unknown; 2000 keeps 29 Feb of year 00.
  const d = new Date(Date.UTC(2000 + yy, mm - 1, dd));
  if (d.getUTCMonth() !== mm - 1 || d.getUTCDate() !== dd) {
    return { ok: false, reason: "date" };
  }
  return { ok: true, reason: "ok" };
}

// Soft signal: a real RFC can fail it. False for anything validateRfc rejects.
export function checkDigitMatches(value) {
  if (!validateRfc(value).ok) return false;
  const rfc = normalize(value);
  return checkDigit(rfc.slice(0, -1)) === rfc.at(-1);
}
// Package rfc validates the structure of a Mexican RFC: format, real date,
// check digit. It does not tell you whether the RFC exists in SAT's registry.
package rfc

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

var (
	ErrFormat = errors.New("rfc: invalid format")
	ErrDate   = errors.New("rfc: date does not exist")
)

// The pattern SAT publishes in its own invoice schema (tdCFDI.xsd, type t_RFC).
var rfcRE = regexp.MustCompile(
	`^[A-Z&Ñ]{3,4}([0-9]{2})(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])[A-Z0-9]{2}[0-9A]$`)

// 39 symbols. The & sits between N and O; the space pads 12-character RFCs.
var alphabet = []rune("0123456789ABCDEFGHIJKLMN&OPQRSTUVWXYZ Ñ")

// Generic holds the placeholders SAT defines for invoices to the general
// public and to foreigners.
var Generic = map[string]bool{"XAXX010101000": true, "XEXX010101000": true}

var cleaner = strings.NewReplacer(
	"n\u0303", "ñ", "N\u0303", "Ñ",
	" ", "", "-", "", "\t", "", "\r", "", "\n", "")

// Normalize composes the Ñ, drops spaces and hyphens, and upper-cases a-z and ñ only.
func Normalize(value string) string {
	return strings.Map(func(r rune) rune {
		switch {
		case r >= 'a' && r <= 'z':
			return r - 32
		case r == 'ñ':
			return 'Ñ'
		}
		return r
	}, cleaner.Replace(value))
}

func valueOf(r rune) int {
	for i, a := range alphabet {
		if a == r {
			return i
		}
	}
	return 0
}

// CheckDigit returns the check digit for an RFC without its last character
// (11 or 12 characters). Ñ takes two bytes in UTF-8, so it works on runes.
func CheckDigit(body string) string {
	runes := []rune(body)
	for len(runes) < 12 {
		runes = append([]rune{' '}, runes...)
	}
	total := 0
	for i, r := range runes[:12] {
		total += valueOf(r) * (13 - i)
	}
	return string(alphabet[(11-total%11)%11])
}

// Validate returns nil, ErrFormat or ErrDate.
func Validate(value string) error {
	m := rfcRE.FindStringSubmatch(Normalize(value))
	if m == nil {
		return ErrFormat
	}
	yy, _ := strconv.Atoi(m[1])
	mm, _ := strconv.Atoi(m[2])
	dd, _ := strconv.Atoi(m[3])
	// The century is unknown; 2000 keeps 29 Feb of year 00.
	// time.Date normalizes impossible dates (31 April becomes 1 May), so compare back.
	d := time.Date(2000+yy, time.Month(mm), dd, 0, 0, 0, 0, time.UTC)
	if int(d.Month()) != mm || d.Day() != dd {
		return ErrDate
	}
	return nil
}

// CheckDigitMatches is a soft signal: a real RFC can fail it.
// It is false for anything Validate rejects.
func CheckDigitMatches(value string) bool {
	if Validate(value) != nil {
		return false
	}
	runes := []rune(Normalize(value))
	last := len(runes) - 1
	return CheckDigit(string(runes[:last])) == string(runes[last])
}

Test cases

Input Shape and date Check digit matches? What it tests
GODE561231GR8 ok yes The example in SAT's document
gode-561231-gr8 ok yes Lower case and hyphens
SAT970701NN3 ok yes SAT's own RFC; 12 characters
A&B010203AB8 ok yes & in a company RFC
ÑAÑE800229XY0 ok yes Ñ, whole or in two pieces, and February 29
YHCU850714LYA ok yes Check digit A
ABCD000229AB4 ok yes February 29 of year 00
XAXX010101000 ok no Generic RFC: the digit would be 4
ABCD010229AB7 date February 29 of a non-leap year
ABC990431ABA date April 31
ABCD991301AB1 format Month 13
GODE561231GRB format The check digit can only be 0-9 or A
GODE561231GR8 format Full-width digits
ßAT970701NN3 format ß is not turned into SS

How it was tested: 38 cases run against the three implementations; 200,000 random inputs (valid keys, wrong digits, impossible dates, odd characters) gave the same result in all three; and 16 public RFCs of companies and government bodies, the kind printed on their invoices, satisfied the algorithm.

What a valid structure does not tell you

An RFC that passes these checks is well formed. Nothing more. It can be a key that was never assigned, one that belongs to someone else, or one SAT has already cancelled. Only the registry answers that.

It is still worth running the offline validation first: it catches typos before you spend a lookup on them, and it lets you tell the person which part is wrong.

Sources

Related services

Keep reading

All guides ›
Tax What to check in a Mexican CFDI before paying

Six checks on the XML of a Mexican e-invoice (CFDI) before paying it, with Python code, and three things the XML cannot tell you.

6 min
Tax SAT Article 69 vs 69-B: differences, Mexico

How SAT's Article 69 lists and the 69-B list differ in Mexico, what risk each one covers and six common mistakes when integrating them.

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
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