aeat.core.identity._tax_id module

Spanish tax-identifier validation (NIF / NIE / CIF) returning canonical strings.

The Agencia Tributaria’s identifier algorithm is shared infrastructure across multiple subpackages — invoice counterparty checks, encrypted master-key NIF canaries, sanitiser fixture validation, and CLI preflight gates. Co-locating the algorithm in core.identity gives every caller a public, layer-respecting import path.

This module differs from core.identity._documents only in its return shape: validate_spanish_tax_id() yields the normalised identifier string, while validate_identity() returns the matching IdentityDocument enum member. Both surfaces raise IdentityError; this module also exports nif_check_letter() for callers that need the shared NIF/NIE checksum table directly.

validate_spanish_tax_id(value)[source]

Validate a Spanish NIF, NIE, or CIF and return its canonical form.

Implements the Agencia Tributaria algorithm:

  • NIF — 8 digits, or current K/L/M plus 7 digits for natural persons without DNI/NIE, followed by a checksum letter drawn from TRWAGMYFPDXBNJZSQVHLCKE indexed by number % 23.

  • NIE — a leading X/Y/Z substituted with 0/1/2 before applying the NIF rule.

  • CIF — a leading letter from ABCDEFGHJNPQRSUVW, 7 digits, and a 1-character control. Leading letters in PQRSNW require a letter control drawn from JABCDEFGHI; leading letters in ABEH require a digit control; all other leaders accept either form (both historically in circulation).

Parameters:

value (str) – Raw tax identifier to validate.

Return type:

str

Returns:

The uppercased, whitespace-trimmed identifier.

Raises:

IdentityError – If the identifier is malformed or the checksum fails.