/** * CNPJ (Cadastro Nacional da Pessoa Jurídica, Brazilian company identifier). * * Numbers from the national register of legal entities have 14 characters. The * first 8 characters identify the company, the following 4 identify a business * unit and the last 2 are check digits. * * Starting July 2026, new CNPJs may be alphanumeric: the first 12 positions * can contain A-Z and 0-9, while the last 2 remain numeric check digits. * Legacy numeric-only CNPJs remain valid. The check digit algorithm (mod 11) * is unchanged; letters use their ASCII code minus 48 (A=17 … Z=42). * * Sources: * * ENTITY */ import * as exceptions from '../exceptions'; import { strings } from '../util'; import { Validator, ValidateReturn } from '../types'; function clean(input: string): ReturnType { return strings.cleanUnicode(input, ' -./'); } function charValue(ch: string): number { return ch.charCodeAt(0) - 48; } function computeDigit(input: string): number { const mlen = input.length + 7; const value = 11 - (input .split('') .map((v, idx) => charValue(v) * (((mlen - idx) % 8) + 2)) .reduce((acc, v) => acc + v) % 11); return value > 9 ? 0 : value; } const impl: Validator = { name: 'Brazilian Company Identifier', localName: 'Cadastro Nacional da Pessoa Jurídica', abbreviation: 'CNPJ', examples: ['16727230000197', '12ABC34501DE35'], formats: ['cc.ccc.ccc/cccc-nn'], compact(input: string): string { const [value, err] = clean(input); if (err) { throw err; } return value; }, format(input: string): string { const [value] = clean(input); const [a, b, c, d, e] = strings.splitAt(value, 2, 5, 8, 12); return `${a}.${b}.${c}/${d}-${e}`; }, validate(input: string): ValidateReturn { const [value, error] = clean(input); if (error) { return { isValid: false, error }; } if (value.length !== 14) { return { isValid: false, error: new exceptions.InvalidLength() }; } if (!strings.isalphanumeric(value)) { return { isValid: false, error: new exceptions.InvalidFormat() }; } const [front, c1, c2] = strings.splitAt(value, 12, 13); if (!strings.isdigits(c1) || !strings.isdigits(c2)) { return { isValid: false, error: new exceptions.InvalidFormat() }; } const d1 = String(computeDigit(front)); const d2 = String(computeDigit(value.slice(0, 13))); if (d1 !== c1 || d2 !== c2) { return { isValid: false, error: new exceptions.InvalidChecksum() }; } return { isValid: true, compact: value, isIndividual: false, isCompany: true, }; }, }; export const { name, localName, abbreviation, examples, formats, validate, format, compact, } = impl;