--- title: "Utilities" description: "Every utility of Brazilian Utils, grouped by family (CPF, CNPJ, CEP, boleto, Pix and more), with its options, examples and edge cases." keywords: ["CPF", "CNPJ", "CEP", "boleto", "Pix", "NF-e", "phone", "license plate", "RENAVAM", "PIS", "CNH", "IBAN", "holidays", "business days", "CBO", "CNAE", "NCM", "CFOP", "validator", "formatter", "parser", "generator"] --- Every function of the package, grouped by family. Each section says what the function does, its options, what it returns on bad input, and shows an example. ## Conventions These rules hold for every function unless its section says otherwise. - **Nothing throws on bad input** (`null`, `undefined`, the wrong type): `isValid*` return `false`, `format*` and `parse*` return `''`, single-item `get*` return `null`, list `get*` return `[]`. The only exceptions are the async `getAddressInfoByCep` and `getCepInfoByAddress`, which reject with typed errors. - **Validators accept the value masked or not**: the usual mask characters (`.`, `-`, `/`) and spaces between or around the groups are ignored, so there is no need to strip formatting first. - **A number is read only when it is a non-negative safe integer**: the functions that take `string | number` treat a negative, fractional, non-finite or unsafe number as bad input (`isValidCep(-20040020)` is `false`, `formatCpf(-1)` and `parseCpf(1.5)` are `''`), since in a number `-` and `.` are not mask characters. - **Formatters mask as far as the value goes**, so they also work as input masks while the user types. `parse*` functions do the reverse and keep only the meaningful characters. - **Generators use `Math.random()`**, so they are fine for tests and fixtures and never for anything security-related. - **Getters return a new array or object on every call**, so mutating a result never affects the next call. - **Every function is synchronous** except `getAddressInfoByCep`, `getCepInfoByAddress` and the deprecated `getMunicipality`. ## CPF ### isValidCpf Check if a CPF is valid. - Returns `false` for a reserved number (all digits the same, such as `00000000000`) and for a wrong check digit. - The reserved numbers are the ones the Receita Federal's [DJE layout](http://normas.receita.fazenda.gov.br/sijut2consulta/anexoOutros.action?idArquivoBinario=36307) lists as not valid. The CPF's own norm, [IN RFB nº 2.172/2024](https://normas.receita.fazenda.gov.br/sijut2consulta/link.action?idAto=135611), has no check digit rule; the rule is the one of the Receita Federal's [e-Financeira manual](http://sped.rfb.gov.br/estatico/33/BBD9A14FFF8CB38ECEEC2FC2D3713AE716DB11/Manual%20e-Financeira%20v%202.1.2-%20Anexo%20II%20-%20Leiautes%20Gerais.pdf) (Anexo II, `REGRA_VALIDA_CPF`, approved by the Ato Declaratório Executivo Cofis nº 10/2026). ```javascript import { isValidCpf } from '@brazilian-utils/brazilian-utils'; isValidCpf('155151475'); // false isValidCpf('111 444 777 35'); // true (whitespace mask) ``` ### formatCpf Format a CPF. - **Options** (`FormatCpfOptions`): `pad` left-pads the value with zeros to 11 digits before masking (default `false`); `obfuscate` hides the first 3 digits and the 2 check digits. An empty value, or one without digits, gives `''` even with `pad`. - `obfuscate` is applied after `pad`. It follows the rule the Leis de Diretrizes Orçamentárias set for publishing a CPF: "ocultar os três primeiros dígitos e os dois dígitos verificadores" ([Lei nº 14.194/2021, art. 149](https://www.planalto.gov.br/ccivil_03/_ato2019-2022/2021/lei/L14194.htm), first set by Lei nº 12.309/2010, art. 87, § 5º; [Lei nº 15.321/2025, art. 163](https://www.planalto.gov.br/ccivil_03/_ato2023-2026/2025/lei/L15321.htm#art163), the LDO for 2026, repeats it). ```javascript import { formatCpf } from '@brazilian-utils/brazilian-utils'; formatCpf('74650688000'); // 746.506.880-00 formatCpf('746506880', { pad: true }); // 007.465.068-80 formatCpf('12345678909', { obfuscate: true }); // ***.456.789-** ``` ### parseCpf Remove CPF formatting, keep only digits, and cap the result to 11 digits. ```javascript import { parseCpf } from '@brazilian-utils/brazilian-utils'; parseCpf('746.506.880-00'); // 74650688000 ``` ### generateCpf Generate a valid random CPF. - The optional `state` argument (`StateCode`, e.g. `"SP"`) fixes the região fiscal digit (the 9th) to that state's code. - `state` ignores letter case and surrounding whitespace (`'sp'` is `'SP'`). Without `state`, or with an unknown code, a random região fiscal digit is drawn. ```javascript import { generateCpf } from '@brazilian-utils/brazilian-utils'; generateCpf(); generateCpf('SP'); // the 9th digit is 8, the SP região fiscal code generateCpf('MG'); // the 9th digit is 6, the MG região fiscal code ``` ### getCpfInfo Read the fields a CPF encodes, as a `CpfInfo`: the 8 digit `base`, the `fiscalRegion` digit (the 9th digit, the Região Fiscal of the Receita Federal the CPF was registered in, `"1"` to `"9"` and `"0"` for the 10ª), the `states` of that region (`StateCode[]`, sorted by state name) and the 2 `checkDigits`. Accepts the same masked or unmasked input as `isValidCpf` and returns `null` for anything that is not a valid CPF. The region is the one of the address given at the first registration: it says nothing about where the holder was born, lives today or asked for the number, and a region with more than one state does not tell which of them it was. | `fiscalRegion` | `states` | | --- | --- | | `"1"` | DF, GO, MT, MS, TO | | `"2"` | AC, AP, AM, PA, RO, RR | | `"3"` | CE, MA, PI | | `"4"` | AL, PB, PE, RN | | `"5"` | BA, SE | | `"6"` | MG | | `"7"` | ES, RJ | | `"8"` | SP | | `"9"` | PR, SC | | `"0"` | RS | ```javascript import { getCpfInfo } from '@brazilian-utils/brazilian-utils'; getCpfInfo('123.456.789-09'); // { // base: '12345678', // fiscalRegion: '9', // states: ['PR', 'SC'], // checkDigits: '09', // } getCpfInfo('12345678900'); // null (invalid check digits) ``` Source: [Receita Federal, "Cadastros: CPF e CNPJ"](https://www.gov.br/receitafederal/pt-br/assuntos/educacao-fiscal/educacao_fiscal/folhetos-orientativos/cadastros-dig.pdf). ## CNPJ ### isValidCnpj Check if a CNPJ is valid. - **Options** (`IsValidCnpjOptions`): `version` picks the accepted format: `1` (default) numeric only, `2` numeric and alphanumeric. Any other value is read as `1`. - Since July 2026 new CNPJs may be alphanumeric, which the default `version: 1` rejects: pass `version: 2` to accept them. - A reserved number (all digits the same) is rejected under both versions; version `2` has no reserved list for letters. - The official character set of the alphanumeric CNPJ is the capital letters `A` to `Z` and the digits (the 2 check digits are always digits). A lower case letter is accepted only as input normalization, like a mask character: the input is upper-cased first. - The Ex1 of question 23 of the Receita Federal's Q&A on the alphanumeric CNPJ, `AA345678/0003-29`, is a misprint: its check digits are `86`, so it is rejected. ```javascript import { isValidCnpj } from '@brazilian-utils/brazilian-utils'; isValidCnpj('15515147234255'); // false isValidCnpj('q0slfmbd7vx439', { version: 2 }); // true (read as Q0SLFMBD7VX439) ``` Source: [Instrução Normativa RFB nº 2.229/2024](http://normas.receita.fazenda.gov.br/sijut2consulta/link.action?idAto=141102) (Anexo XV of IN RFB nº 2.119/2022, weights "da direita para esquerda" as corrected by the retificação in the DOU of 25/10/2024), [Receita Federal, Manual do DV do CNPJ](https://www.gov.br/receitafederal/pt-br/centrais-de-conteudo/publicacoes/documentos-tecnicos/cnpj/manual-dv-cnpj.pdf), [CNPJ alfanumérico](https://www.gov.br/receitafederal/pt-br/acesso-a-informacao/acoes-e-programas/programas-e-atividades/cnpj-alfanumerico). ### formatCnpj Format a CNPJ. - **Options** (`FormatCnpjOptions`): `pad` left-pads the value with zeros to 14 characters before masking (default `false`); `version` picks the format, `1` (default) numeric only, `2` alphanumeric; `obfuscate` hides the first 2 digits and the 2 check digits. An empty value, or one without digits, gives `''` even with `pad`. - Version `2` keeps letters and digits, a lower case letter upper-cased first since the official set is `A` to `Z`; version `1` keeps digits only. Since July 2026 new CNPJs may be alphanumeric, so pass `version: 2` to keep their letters. - `obfuscate` works in both versions and is applied after `pad`. It is a convention of this library, not an official rule: no law or Receita Federal act sets a masking rule for the CNPJ, whose data are public, the [ANPD](https://www.gov.br/anpd/pt-br/centrais-de-conteudo/documentos-tecnicos-orientativos/estudo_tecnico_sobre_anonimizacao_de_dados_na_lgpd_uma_visao_de_processo_baseado_em_risco_e_tecnicas_computacionais.pdf) says "não há um padrão para o mascaramento", and the [Banco Central's Pix rules](https://www.bcb.gov.br/content/estabilidadefinanceira/pix/Regulamento_Pix/IV_RequisitosMinimosparaExperienciadoUsuario.pdf) show the CNPJ in full where they mask the CPF; it hides the first 2 characters and the 2 check digits, after the CPF rule. ```javascript import { formatCnpj } from '@brazilian-utils/brazilian-utils'; formatCnpj('24522200000174'); // 24.522.200/0001-74 formatCnpj('245222000174', { pad: true }); // 00.245.222/0001-74 formatCnpj('12OUT345000199', { version: 2 }); // 12.OUT.345/0001-99 formatCnpj('12345678000195', { obfuscate: true }); // **.345.678/0001-** ``` ### parseCnpj Remove CNPJ formatting, return a normalized value, and cap the result to 14 characters. - **Options** (`ParseCnpjOptions`): `version` picks the format: `1` (default) keeps digits only, `2` keeps letters and digits, a lower case letter upper-cased since the official set is `A` to `Z` (`parseCnpj('12.abc.345/01de-35', { version: 2 })` returns `'12ABC34501DE35'`). Since July 2026 new CNPJs may be alphanumeric, so the default drops their letters: pass `version: 2` to keep them. ```javascript import { parseCnpj } from '@brazilian-utils/brazilian-utils'; parseCnpj('24.522.200/0001-74'); // 24522200000174 parseCnpj('12.OUT.345/0001-99', { version: 2 }); // 12OUT345000199 ``` ### generateCnpj Generate a valid random CNPJ. - The first argument is either the version, `1` (default) numeric or `2` alphanumeric, or a `GenerateCnpjParams` object with `version` plus `branch`. - `branch` is the "número de ordem" (filial) block, an integer from 1 to 9999 (random by default). An invalid `branch` is ignored. The block stays numeric in both versions. - A random ordem block is never `0000`: the establishments of a root are numbered from `0001`, the matriz, on, so that block is never assigned. ```javascript import { generateCnpj } from '@brazilian-utils/brazilian-utils'; generateCnpj(); generateCnpj(2); // alphanumeric CNPJ, e.g. 'Q0SLFMBD7VX439' generateCnpj({ branch: 3 }); // ordem block '0003', e.g. '12345678000357' generateCnpj({ version: 2, branch: 1 }); // alphanumeric CNPJ whose ordem block is '0001' ``` ### getCnpjInfo Parse a CNPJ into the fields the number encodes. Accepts the same input forms as `isValidCnpj` and returns `null` whenever it would return `false` for the same arguments, so an alphanumeric CNPJ read under version `1` is `null`. - **Options** (`GetCnpjInfoOptions`): `version` is read the way `isValidCnpj` reads it, `1` (default) the numeric-only format, `2` both the numeric and the alphanumeric one. - Returns a `CnpjInfo`, the 14 positions as Anexo XV lays them out: 8 (`root`, the raiz that identifies the entity) + 4 (`branch`, the establishment, called número de ordem by the Receita Federal) + 2 (`checkDigits`, always numeric). `branch` is named after the `branch` parameter of `generateCnpj`, which fills the same four positions. - `isInitialHeadquarters` tells whether the branch is `0001`, the one the Receita Federal gives the headquarters (matriz) when the root is registered. A filial can later become the headquarters while keeping its número de ordem, so only the Receita Federal registry tells the current headquarters. - The fields of an alphanumeric CNPJ are returned upper cased. ```javascript import { getCnpjInfo } from '@brazilian-utils/brazilian-utils'; getCnpjInfo('12.345.678/0001-95'); // { // root: '12345678', // branch: '0001', // checkDigits: '95', // isInitialHeadquarters: true // } getCnpjInfo('12.abc.345/01de-35', { version: 2 }); // { // root: '12ABC345', // branch: '01DE', // checkDigits: '35', // isInitialHeadquarters: false // } getCnpjInfo('12.ABC.345/01DE-35'); // null (alphanumeric, read under version 1) getCnpjInfo('12.345.678/0001-90'); // null (bad check digits) ``` Source: [Instrução Normativa RFB nº 2.229/2024](http://normas.receita.fazenda.gov.br/sijut2consulta/link.action?idAto=141102), whose Anexo Único is the Anexo XV of IN RFB nº 2.119/2022 and lays the 14 positions out, [Receita Federal Q&A on the alphanumeric CNPJ](https://www.gov.br/receitafederal/pt-br/centrais-de-conteudo/publicacoes/perguntas-e-respostas/cnpj/cnpj-alfanumerico.pdf) (questions 21, 23 and 25). ## CEP and address ### isValidCep Check if a CEP ([brazilian postal code](https://en.wikipedia.org/wiki/C%C3%B3digo_de_Endere%C3%A7amento_Postal)) is valid. - Accepts a `string` or a `number`. A CEP that starts with `0` has to be a string, since a number cannot keep the leading zero, and a number is only read when it is a non-negative safe integer. - Spaces, dots, hyphens and slashes are ignored. Any other character makes the value invalid. - `getAddressInfoByCep` and `formatCep` with `pad: true` are more lenient with numbers: they left-pad a number to 8 digits (`1310100` is `01310-100`), while `isValidCep` and `getStateByCep` read `1310100` as 7 digits and reject it. ```javascript import { isValidCep } from '@brazilian-utils/brazilian-utils'; isValidCep('01310100'); // true isValidCep('92500-000'); // true (hyphen between groups) isValidCep('92.500-000'); // true (dot and hyphen) isValidCep('013 10 100'); // true (spaces anywhere between the digits) isValidCep(20040020); // true (number input) isValidCep(-20040020); // false (not a non-negative safe integer) isValidCep('9250000A'); // false (letters are rejected) isValidCep('12345'); // false (invalid length) ``` ### formatCep Format a CEP ([brazilian postal code](https://en.wikipedia.org/wiki/C%C3%B3digo_de_Endere%C3%A7amento_Postal)). - **Options** (`FormatCepOptions`): `pad` left-pads the value with zeros to 8 digits before masking (default `false`). An empty value, or one without digits, gives `''` even with `pad`. - A CEP that starts with `0` given as a number loses that zero: pass a string or use `pad`. A number is only read when it is a non-negative safe integer; any other number returns `''`. ```javascript import { formatCep } from '@brazilian-utils/brazilian-utils'; formatCep('92500000'); // 92500-000 formatCep('9250000', { pad: true }); // 09250-000 formatCep(-92500000); // '' (not a non-negative safe integer) ``` ### parseCep Remove CEP formatting, keep only digits, and cap the result to 8 digits. ```javascript import { parseCep } from '@brazilian-utils/brazilian-utils'; parseCep('92500-000'); // 92500000 ``` ### generateCep Generate a random CEP. A CEP has no check digit, so the CEP is drawn inside the ranges the Correios assign to the states, each CEP with the same chance. It always belongs to a state, so `getStateByCep` never answers `null` for it; `00000-000` to `00999-999` and `78900-000` to `78999-999`, which no state owns, are never generated. A range is the block a state owns, not a promise that every CEP in it is in use, so the CEP may not be the CEP of a real address. ```javascript import { generateCep } from '@brazilian-utils/brazilian-utils'; generateCep(); // '92500000' ``` ### getAddressInfoByCep Fetch the address of a CEP from several providers at once and resolve to the first successful answer. The result is an `AddressInfo`: `cep`, `state`, `city`, `neighborhood` and `street`. - **Options** (`GetAddressInfoByCepOptions`): - `providers` (`CepProvider[]`) lists the providers to race (default `['viacep', 'brasilapi']`). `'widenet'` is deprecated, left out of the default list and usually unavailable: its endpoint now redirects to `ws.apicep.com`, which answered 502 when last checked, so it only adds a failing provider to the race. - `timeoutMs` (`number`) bounds the whole lookup, retries included (default: no limit). When it runs out, every request is aborted and the call rejects with `GetAddressInfoByCepServiceError`. - `signal` (`AbortSignal`) cancels the lookup; the call rejects with `signal.reason`, the same as `fetch`. - Accepts a string or a number. A string has any non-digit characters stripped (`'CEP 01310-100'` is `01310100`) and has to leave 8 digits. A number is left-padded with zeros to 8 digits, since it cannot carry the leading zero of a São Paulo CEP, but only from `1000000` (`01000-000`, the lowest CEP the Correios assign) up. A smaller, negative or fractional number is rejected with `GetAddressInfoByCepValidationError` before any request is made. - Retries transient network failures per provider. - Rejects with `GetAddressInfoByCepValidationError` when the CEP is invalid, `providers` names no known provider or `timeoutMs` is not a positive finite number, with `GetAddressInfoByCepNotFoundError` when every provider failed and at least one reported the CEP as unknown, and with `GetAddressInfoByCepServiceError` when every provider failed for another reason. - BrasilAPI answers 404 both for an unknown CEP and when the services behind it are down, so its 404 only counts as "unknown CEP" when no other provider failed to answer. - An address is only accepted when it agrees with the CEP asked for: its digits, left-padded with zeros to 8 (a provider that answers `1310100` for `01310-100` means the same CEP), must be the CEP, and its state, when it names one, must be the state that owns the CEP range (see `getStateByCep`). Otherwise that provider counts as not knowing the CEP. BrasilAPI, for instance, answered `99999-999`, a Rio Grande do Sul CEP, with a city of Paraná. - Once the lookup settles, the requests of the providers that lost the race are aborted. - All three extend `GetAddressInfoByCepError`, so one `catch` covers them. ```javascript import { getAddressInfoByCep, GetAddressInfoByCepNotFoundError } from '@brazilian-utils/brazilian-utils'; // Using the default providers (['viacep', 'brasilapi']) const address = await getAddressInfoByCep('01310100'); // { cep: '01310100', state: 'SP', city: 'São Paulo', neighborhood: 'Bela Vista', street: 'Avenida Paulista' } // Using a specific provider, and telling an unknown CEP from a failure try { await getAddressInfoByCep('01310-100', { providers: ['brasilapi'] }); } catch (error) { if (error instanceof GetAddressInfoByCepNotFoundError) { // no provider knows the CEP } } // Using number input (will be padded automatically) const addressFromNumber = await getAddressInfoByCep(1310100); // Giving up after 5 seconds const addressWithinFiveSeconds = await getAddressInfoByCep('01310100', { timeoutMs: 5000 }); ``` ### getCepInfoByAddress Fetch the CEPs of an address from ViaCEP. Resolves to an array of `CepAddressInfo`. - The argument (`GetCepInfoByAddressParams`) carries `federalUnit`, `city` and `street`. `federalUnit` may be lowercase; `city` and `street` are trimmed and stripped of accents before the query, and each must be a string of at least 3 characters after that, the minimum ViaCEP accepts. - Rejects with `GetCepInfoByAddressValidationError` when the UF, city or street is missing or invalid (a blank value, a value that is not a string, or a city or street under 3 characters, all rejected before any request), with `GetCepInfoByAddressNotFoundError` when no address matches, and with `GetCepInfoByAddressError` when ViaCEP answers with an HTTP error status. - Retries transient network failures, as `getAddressInfoByCep` does. - Each item carries the ViaCEP payload unchanged, under ViaCEP's own field names. - ViaCEP caps the list at 50 addresses, so a short street name that matches more streets returns only the first 50. ```javascript import { getCepInfoByAddress } from '@brazilian-utils/brazilian-utils'; const ceps = await getCepInfoByAddress({ federalUnit: 'MG', city: 'Ouro Preto', street: 'Rua Direita' }); // [ // { // cep: '35411-152', // logradouro: 'Rua Direita', // complemento: '', // unidade: '', // bairro: 'Riacho (Amarantina)', // localidade: 'Ouro Preto', // uf: 'MG', // estado: 'Minas Gerais', // regiao: 'Sudeste', // ibge: '3146107', // gia: '', // ddd: '31', // siafi: '4921' // } // ] ``` ## Boleto ### isValidBoleto Check if a boleto ([brazilian payment method](https://en.wikipedia.org/wiki/Boleto)) is valid. - Accepts the 47 digit "cobrança bancária" linha digitável, its 44 digit barcode (bank code, código de moeda `9`, the módulo 11 check digit in position 5, fator de vencimento, amount and free field) and, for the "boleto de arrecadação", either its 48 digit linha digitável or its 44 digit barcode. A 44 digit value starting with `8` is only ever an arrecadação barcode (the `8` is the FEBRABAN product identifier of the arrecadação), so a cobrança bancária barcode of a bank code from `800` to `899` (only `804` exists) is not accepted in barcode form, as the two could not be told apart; its 47 digit linha digitável is accepted. Up to 2.4.0 the cobrança bancária barcode was rejected. - The usual mask characters (whitespace, `.`, `-` and `/`) are accepted between digits; any other character makes the value invalid, so `abc` + a linha digitável + `zzz` is rejected, not read as its digits (up to 2.4.0 every non-digit was dropped). - The código de moeda (position 4 of the cobrança bancária barcode and linha digitável) must be `9` (real), the only code Carta-Circular BCB nº 2.926/2000 assigns. The one exception is the "Situação 2" slip of the FEBRABAN Convenção da Cobrança, issued by an institution identified only by its ISPB: bank code `988`, código de moeda `0`, fator de vencimento `0000` and the ISPB, padded with zeros, where the amount would be. Any other digit is rejected. ```javascript import { isValidBoleto } from '@brazilian-utils/brazilian-utils'; isValidBoleto('00190000090114971860168524522114675860000102656'); // true isValidBoleto('00196758600001026560000001149718606852452211'); // true (cobrança bancária barcode) isValidBoleto('846100000005246100291102005460339004695895061080'); // true (boleto de arrecadação) isValidBoleto('00170000010114971860168524522114275860000102656'); // false (código de moeda 7) isValidBoleto('abc00190000090114971860168524522114675860000102656zzz'); // false (letters around the digits) isValidBoleto('98800000060114971860168524522114100000018236120'); // true (Situação 2: bank 988, moeda 0, ISPB) ``` Source: [Carta-Circular BCB nº 2.926/2000](https://www.bcb.gov.br/pre/normativos/c_circ/2000/pdf/c_circ_2926_v1_O.pdf), [FEBRABAN, Layout Padrão de Arrecadação, Versão 08](https://cmsarquivos.febraban.org.br/Arquivos/documentos/PDF/Layout%20-%20C%C3%B3digo%20de%20Barras%20-%20Vers%C3%A3o%208%20-%2011_05_2026.pdf) (in force from 01/06/2026), [FEBRABAN, Convenção da Cobrança](https://cmsarquivos.febraban.org.br/Arquivos/documentos/PDF/Conven%C3%A7%C3%A3o%20da%20Cobran%C3%A7a%20-%2005_02_2021_f.pdf). ### formatBoleto Format a boleto number. - **Options** (`FormatBoletoOptions`): `pad` left-pads the value with zeros to the length of the pattern before masking (default `false`). An empty value, or one without digits, gives `''` even with `pad`. - A 48 digit linha digitável starting with `8` gets the arrecadação mask: four blocks of 11 digits, each followed by its check digit. The 44 digit arrecadação barcode keeps the "cobrança bancária" mask. ```javascript import { formatBoleto } from '@brazilian-utils/brazilian-utils'; formatBoleto('00190000090114971860168524522114675860000102656'); // 00190.00009 01149.718601 68524.522114 6 75860000102656 formatBoleto('1900000901149', { pad: true }); // 00000.00000 00000.000000 00000.000000 0 01900000901149 formatBoleto('846100000005246100291102005460339004695895061080'); // 84610000000-5 24610029110-2 00546033900-4 69589506108-0 (48 digit arrecadação linha digitável) formatBoleto('84610000000246100291100054603390069589506108'); // 84610.00000 02461.002911 00054.603390 0 69589506108 (44 digit arrecadação barcode keeps the bancária mask) ``` Source: [FEBRABAN, Layout Padrão de Arrecadação, Versão 08](https://cmsarquivos.febraban.org.br/Arquivos/documentos/PDF/Layout%20-%20C%C3%B3digo%20de%20Barras%20-%20Vers%C3%A3o%208%20-%2011_05_2026.pdf) (in force from 01/06/2026). ### parseBoleto Remove boleto formatting, keep only digits, and cap the result to 47 digits (48 for boleto de arrecadação). ```javascript import { parseBoleto } from '@brazilian-utils/brazilian-utils'; parseBoleto('00190.00009 01149.718601 68524.522114 6 75860000102656'); // 00190000090114971860168524522114675860000102656 ``` Source: [Carta-Circular BCB nº 2.926/2000](https://www.bcb.gov.br/pre/normativos/c_circ/2000/pdf/c_circ_2926_v1_O.pdf), [FEBRABAN, Layout Padrão de Arrecadação, Versão 08](https://cmsarquivos.febraban.org.br/Arquivos/documentos/PDF/Layout%20-%20C%C3%B3digo%20de%20Barras%20-%20Vers%C3%A3o%208%20-%2011_05_2026.pdf) (in force from 01/06/2026). ### generateBoleto Generate a valid random boleto. - Pass `{ type: 'arrecadacao' }` (`GenerateBoletoParams`) for a 48 digit boleto de arrecadação instead of the default `'bancario'` (cobrança bancária, 47 digits). - A cobrança bancária slip carries the código de moeda `9` and a fator de vencimento of `0000` (no due date) or `1000` to `9999`; `0001` to `0999` denote no date. ```javascript import { generateBoleto } from '@brazilian-utils/brazilian-utils'; generateBoleto(); // "00190000090114971860168524522114675860000102656" generateBoleto({ type: 'arrecadacao' }); // "846100000005246100291102005460339004695895061080" ``` Source: [Carta-Circular BCB nº 2.926/2000](https://www.bcb.gov.br/pre/normativos/c_circ/2000/pdf/c_circ_2926_v1_O.pdf), [FEBRABAN, Layout Padrão de Arrecadação, Versão 08](https://cmsarquivos.febraban.org.br/Arquivos/documentos/PDF/Layout%20-%20C%C3%B3digo%20de%20Barras%20-%20Vers%C3%A3o%208%20-%2011_05_2026.pdf) (in force from 01/06/2026). ### getBoletoInfo Extract information from a boleto (amount, expiration date, bank code). Returns `null` when the value is not a valid boleto. - **Options** (`GetBoletoInfoOptions`): `referenceDate` resolves the "fator de vencimento" cycle as of that date instead of now. - Reads the 47 digit linha digitável and the 44 digit barcode of a cobrança bancária slip, and the arrecadação forms, the same way as `isValidBoleto` accepts them. - Returns a `BoletoInfo`: `amount` in cents, `expirationDate` and the three digit `bankCode`. `expirationDate` is `null` when the slip carries no fator de vencimento (a factor below `1000`). - The fator de vencimento cycle reset on 22/02/2025, so a factor can mean either of two dates 9000 days apart. No FEBRABAN communiqué on the reset is published; the rule is in bank manuals, such as [Bradesco's](https://banco.bradesco/assets/pessoajuridica/pdf/4008-524-0121-layout-cobranca-versao-portugues.pdf) (Versão 17). `referenceDate` picks between them; pass it whenever the answer has to stay stable. - The windows are 3000 days back and 5500 days ahead of `referenceDate`: a slip due up to 3499 days (about 9.5 years) before it keeps its date, and one due 3500 days (about 9.6 years) or more before it is read as the next cycle (a date in the future), so to read an old slip pass a `referenceDate` near its issue date. A `referenceDate` that is not a valid `Date` is ignored and now is used. - A boleto de arrecadação has `bankCode: ''` and `expirationDate: null`, plus `type: 'arrecadacao'`, `segment`, `value` (the amount in reais) and `hasEffectiveValue`. - A FEBRABAN Convenção da Cobrança "Situação 2" slip (bank code `988`, código de moeda `0`) carries the issuer's ISPB where the amount would be: it comes back as `ispb`, with `amount: 0`. ```javascript import { getBoletoInfo } from '@brazilian-utils/brazilian-utils'; getBoletoInfo('00190000090114971860168524522114675860000102656'); // { amount: 102656, expirationDate: Date, bankCode: '001' } getBoletoInfo('00196758600001026560000001149718606852452211'); // same slip read from its 44 digit barcode getBoletoInfo('00190000090114971860168524522114675860000102656', { referenceDate: new Date(2018, 6, 1) }); // Resolves the fator de vencimento cycle as of 2018-07-01 getBoletoInfo('98800000060114971860168524522114100000018236120'); // { amount: 0, expirationDate: null, bankCode: '988', ispb: '18236120' } getBoletoInfo('846100000005246100291102005460339004695895061080'); // { amount: 2461, expirationDate: null, bankCode: '', type: 'arrecadacao', segment: 4, value: 24.61, hasEffectiveValue: true } getBoletoInfo('invalid'); // null ``` Source: [Carta-Circular BCB nº 2.926/2000](https://www.bcb.gov.br/pre/normativos/c_circ/2000/pdf/c_circ_2926_v1_O.pdf), [FEBRABAN, Layout Padrão de Arrecadação, Versão 08](https://cmsarquivos.febraban.org.br/Arquivos/documentos/PDF/Layout%20-%20C%C3%B3digo%20de%20Barras%20-%20Vers%C3%A3o%208%20-%2011_05_2026.pdf) (in force from 01/06/2026), [FEBRABAN, Convenção da Cobrança](https://cmsarquivos.febraban.org.br/Arquivos/documentos/PDF/Conven%C3%A7%C3%A3o%20da%20Cobran%C3%A7a%20-%2005_02_2021_f.pdf). ## Pix ### isValidPixKey Check if a Pix key (chave Pix) is valid: a CPF, a CNPJ, an e-mail address, a Brazilian mobile phone number or a random EVP key, per the DICT key formats. - **Options** (`IsValidPixKeyOptions`): `accept` (`PixKeyType[]`, default all of them) lists the kinds of key that count as valid; `[]` rejects everything. - Same recognition rules as `getPixKeyInfo`. ```javascript import { isValidPixKey } from '@brazilian-utils/brazilian-utils'; isValidPixKey('123.456.789-09'); // true isValidPixKey('fulano@example.com'); // true isValidPixKey('(11) 98765-4321'); // true isValidPixKey('71c7d9be-4b85-4e43-9f1c-1f3b8b4e9a2d'); // true isValidPixKey('(11) 3000-0000'); // false (landlines are not Pix keys) isValidPixKey('123.456.789-09', { accept: ['email', 'evp'] }); // false isValidPixKey('not a key'); // false ``` Source: [Manual de Padrões para Iniciação do Pix](https://www.bcb.gov.br/content/estabilidadefinanceira/pix/Regulamento_Pix/II_ManualdePadroesparaIniciacaodoPix.pdf), [DICT API 2.12.1](https://www.bcb.gov.br/content/estabilidadefinanceira/pix/API-DICT.html) and its [changelog](https://www.bcb.gov.br/content/estabilidadefinanceira/pix/changelog.html), [pix-api](https://github.com/bacen/pix-api). ### getPixKeyInfo Identify a Pix key and normalize it to the canonical form the DICT expects inside a BR Code. Returns `null` when the value is not a valid Pix key. - Returns a `PixKeyInfo` with the `type` (`PixKeyType`) and the `value`. - The canonical `value` is digits for a CPF or CNPJ (letters upper-cased), a lowercase e-mail, an E.164 phone or a lowercase UUID. - An 11 digit value valid as both CPF and mobile phone is read as a CPF, unless written as a phone (`+55` prefix or DDD in parentheses). - An e-mail is checked, once lowercased, against the pattern the DICT API registers and its 77 character limit, not against `isValidEmail`: the local part may carry any of ``.!#$'*+/=?^_`{|}~-``, dots included anywhere, and the domain may be a single label (`a@localhost`). The pattern is the one of DICT API 2.12.1, which has had no `&` since version 2.6.0 (27/09/2025). ```javascript import { getPixKeyInfo } from '@brazilian-utils/brazilian-utils'; getPixKeyInfo('123.456.789-09'); // { type: 'cpf', value: '12345678909' } getPixKeyInfo('Fulano@Example.COM '); // { type: 'email', value: 'fulano@example.com' } getPixKeyInfo('a{b}@example.com'); // { type: 'email', value: 'a{b}@example.com' } (DICT pattern, isValidEmail rejects it) getPixKeyInfo('a&b@example.com'); // null (no & since DICT API 2.6.0) getPixKeyInfo('(11) 98765-4321'); // { type: 'phone', value: '+5511987654321' } getPixKeyInfo('71C7D9BE-4B85-4E43-9F1C-1F3B8B4E9A2D'); // { type: 'evp', value: '71c7d9be-4b85-4e43-9f1c-1f3b8b4e9a2d' } getPixKeyInfo('(11) 3000-0000'); // null (a landline is not a Pix key) getPixKeyInfo('51998259765'); // { type: 'cpf', value: '51998259765' } (also a valid phone) getPixKeyInfo('+5551998259765'); // { type: 'phone', value: '+5551998259765' } ``` Source: [Manual de Padrões para Iniciação do Pix](https://www.bcb.gov.br/content/estabilidadefinanceira/pix/Regulamento_Pix/II_ManualdePadroesparaIniciacaodoPix.pdf), [DICT API 2.12.1](https://www.bcb.gov.br/content/estabilidadefinanceira/pix/API-DICT.html) and its [changelog](https://www.bcb.gov.br/content/estabilidadefinanceira/pix/changelog.html). ### isValidPixPayload Check if a Pix BR Code payload (the string behind a Pix QR Code and behind "Pix copia e cola") is valid under the Manual de Padrões para Iniciação do Pix and, where it is silent, the EMV QR Code specification it builds on. - The payload must start with the format indicator `000201`. - The TLV structure, the CRC-16 and the mandatory objects (format indicator, a 4 digit category code, currency, country, merchant name and city) are checked. An object ID may not repeat at the same level, and the CRC (`63`) must be the last object of the payload, not eight characters inside another one. - One "Merchant Account Information" template (IDs 26 to 51) must carry the `br.gov.bcb.pix` GUI with a key (static) or a PSP URL (dynamic), never both. - The key is written in the DICT form (§2.5.1): the one `getPixKeyInfo` returns unchanged, so `12345678909` passes and `123.456.789-09` does not. Whether it is registered cannot be told from the payload. The PSP URL has at most 77 characters (§2.5.2). - The merchant name has at most 25 characters and the city at most 15; the country is `BR` in uppercase. Their characters are not restricted (neither manual does, and EMV types them as `ans`), so a name with accents is accepted, though `generatePixPayload` folds both to printable ASCII. - No BCB manual states the case of the CRC or of `BR`: the only case rule they give is for the GUI, and every official example writes both in uppercase. Accepting a lowercase CRC (`1d3d`) and rejecting `br` are choices of this library, as in 2.4.0. - Object `01` (Point of Initiation Method) is optional and must be `11` or `12` when present. - Object `62` (Additional Data Field) is mandatory and carries the `txid` (62-05), "sempre presente em um BR Code": `***` or 1 to 25 letters and digits (§2.6.2); with a PSP URL any value stands, since §2.7 has the payer ignore it. The `-` of the Manual do BR Code example `RP12345678-2019` is outside the Pix character set of §2.6.2, so that static example is rejected. - An amount (`54`) is digits with an optional `.` and at most two decimals (`98.73`, `98` and `98.` are the EMV examples), at most 13 characters, and greater than zero, except in a Pix Saque BR Code (8 digit `fss` in sub-object 26-03) and next to a PSP location, where the Pix API gives it `0.00` (the Manual do BR Code lists `"0"` among its examples). - Unreserved Templates (IDs 80 to 99) are ignored. ```javascript import { isValidPixPayload } from '@brazilian-utils/brazilian-utils'; isValidPixPayload( '00020126580014br.gov.bcb.pix0136123e4567-e12b-12d1-a456-426655440000' + '5204000053039865802BR5913Fulano de Tal6008BRASILIA62070503***63041D3D' ); // true isValidPixPayload('00020126580014br.gov.bcb.pix...'); // false (broken CRC) ``` Source: [Manual do BR Code](https://www.bcb.gov.br/content/estabilidadefinanceira/spb_docs/ManualBRCode.pdf), [Manual de Padrões para Iniciação do Pix](https://www.bcb.gov.br/content/estabilidadefinanceira/pix/Regulamento_Pix/II_ManualdePadroesparaIniciacaodoPix.pdf). ### getPixPayloadInfo Parse a Pix BR Code payload into its fields. Accepts what `isValidPixPayload` accepts and returns `null` for anything else, never a partial result. - Returns a `PixPayloadInfo`: `merchantName`, `merchantCity`, `pointOfInitiation` and either `key` (static) or `url` (dynamic). - `amount`, `txid`, `description` and `withdrawalFacilitator` (the `fss` of a Pix Saque) are present only when the payload carries them. `txid` is absent for the `***` marker. - `pointOfInitiation` (`PixPointOfInitiation`) is `"dynamic"` when the payload carries a PSP location (a dynamic QR Code in the Pix manual, §2.4.2) or marks itself single use with object `01` = `"12"` (§2.7.2), `"static"` otherwise. A key payload with `01` = `"12"` is therefore `"dynamic"`; `url` and `key` tell the two kinds of QR Code of the manual apart. - With a PSP location, `amount` and `txid` are ignored and left out, as §2.7 of the manual mandates ("Se preenchidos, seu conteúdo deve ser ignorado"). ```javascript import { getPixPayloadInfo } from '@brazilian-utils/brazilian-utils'; getPixPayloadInfo( '00020126580014br.gov.bcb.pix0136123e4567-e12b-12d1-a456-426655440000' + '5204000053039865802BR5913Fulano de Tal6008BRASILIA62070503***63041D3D' ); // { // merchantName: 'Fulano de Tal', // merchantCity: 'BRASILIA', // pointOfInitiation: 'static', // key: '123e4567-e12b-12d1-a456-426655440000' // } ``` Source: [Manual do BR Code](https://www.bcb.gov.br/content/estabilidadefinanceira/spb_docs/ManualBRCode.pdf), [Manual de Padrões para Iniciação do Pix](https://www.bcb.gov.br/content/estabilidadefinanceira/pix/Regulamento_Pix/II_ManualdePadroesparaIniciacaodoPix.pdf). ### generatePixPayload Generate the payload of a Pix BR Code. Exactly one of `params.key` or `params.url` must be given; `null` is returned when both or neither are given. - **Params** (`GeneratePixPayloadParams`): `key` or `url`, `merchantName`, `merchantCity`, and the optional `amount`, `txid` and `description`. - With `key` the payload is static and the key is normalized by `getPixKeyInfo`. With `url` it is dynamic (object `01` set to `12`) and cannot carry `amount` or `txid`. - `url` is a PSP location: host and path, no scheme (`pix.example.com/qr/v2/1234`), at most 77 characters. - `amount` takes two decimal places; `0.005`, `123.456` or a value that rounds to `0.00` is rejected. - `txid` is 1 to 25 characters of `[A-Za-z0-9]` (default `***`). - `merchantName`, `merchantCity` and `description` lose their accents and are truncated to 25, 15 and what is left of the template. ```javascript import { generatePixPayload } from '@brazilian-utils/brazilian-utils'; generatePixPayload({ key: '123.456.789-09', merchantName: 'Fulano de Tal', merchantCity: 'Brasília', amount: 123.45 }); // "00020126330014br.gov.bcb.pix0111123456789095204000053039865406123.455802BR5913Fulano de Tal6008Brasilia62070503***630479EE" generatePixPayload({ url: 'pix.example.com/qr/v2/1234', merchantName: 'Fulano de Tal', merchantCity: 'Brasília' }); // "00020101021226480014br.gov.bcb.pix2526pix.example.com/qr/v2/12345204000053039865802BR5913Fulano de Tal6008Brasilia62070503***6304FC66" generatePixPayload({ merchantName: 'Fulano', merchantCity: 'Brasília' }); // null (neither key nor url) ``` Source: [Manual do BR Code](https://www.bcb.gov.br/content/estabilidadefinanceira/spb_docs/ManualBRCode.pdf), [Manual de Padrões para Iniciação do Pix](https://www.bcb.gov.br/content/estabilidadefinanceira/pix/Regulamento_Pix/II_ManualdePadroesparaIniciacaodoPix.pdf). ## NF-e key ### isValidNfeKey Check if a DF-e access key (chave de acesso) is valid. Covers every DF-e with a 44 character access key; the CF-e-SAT (59) is out. - Models: NF-e (55), NFC-e (65), CT-e (57), MDF-e (58), CT-e OS (67), GTV-e (64), BP-e (63), NF3e (66) and NFCom (62). - Every character is a digit except positions 7 to 18, the root and order of the issuer's CNPJ, which may hold the letters of an alphanumeric CNPJ: the current schemas (NF-e PL_010 `TChNFe`, CT-e PL_CTe_400_RTC, MDF-e 3.00b, NFCom) type the key as `[0-9]{6}[0-9A-Z]{12}[0-9]{26}`, in production for the NF-e from 01/07/2026 (NT 2026.004). A letter anywhere else, the CNPJ check digits in positions 19 and 20 included, is rejected. The schema admits upper case only; lower case is read as upper case, as `isValidCnpj` does with `{ version: 2 }`. A non-ASCII letter that upper cases into an ASCII one (`ſ`, `ß`) is rejected. - The 44 characters may be grouped in 4 by whitespace, `.`, `-` or `/`. The XML `Id` prefixes (`NFe`, `CTe`, `MDFe`, `BPe`, `NF3e`, `NFCom`) are stripped first. - `tpEmis` must be one the MOC of that model assigns (table below). - For NF-e and NFC-e the `cNF` must pass rule B03-10 of the MOC (no repeated or sequential values, not the document number). The rule applies to the documents sent after NT 2019.001, and NF-e software commonly used a `cNF` equal to the document number before it, so a key authorised earlier can be turned down. - The check digits of the issuer's CPF or CNPJ are not checked, only the key's own check digit. Read the key with `getNfeKeyInfo` and pass its `taxId` to `isValidCnpj`, or the last 11 digits of a zero padded `taxId` to `isValidCpf`, to check the issuer as well. - A document number of all zeros is rejected. The check digit is a modulus 11 over the first 43 characters, each valued at its ASCII code minus 48 (`A` = 17 ... `Z` = 42), as NT Conjunta 2025.001 sets it. | Model | `tpEmis` accepted | | --- | --- | | NF-e (55), NFC-e (65) | 1 to 7 and 9 | | CT-e (57) | 1, 3, 4, 5, 7, 8 | | CT-e OS (67) | 1, 5, 7, 8 | | GTV-e (64) | 1, 2, 7, 8 (see below) | | MDF-e (58) | 1, 2, 3 | | BP-e (63), NF3e (66), NFCom (62) | 1, 2 | For the GTV-e, the current CT-e schema package (PL_CTe_400_RTC) enumerates `tpEmis` 1 (normal) and 2 (contingência off-line) only; the earlier PL_CTe_400 also had 7 and 8 (autorização pela SVC-RS and SVC-SP). The key carries no schema version, so the library accepts all four, and the keys of GTV-e authorised under the earlier package keep validating. ```javascript import { isValidNfeKey } from '@brazilian-utils/brazilian-utils'; isValidNfeKey('35170458716523000119550010000000121000123458'); // true (NF-e, SP) isValidNfeKey('NFe35170458716523000119550010000000121000123458'); // true (XML Id prefix) isValidNfeKey('CTe35170458716523000119570010000000128000123452'); // true (CT-e authorised by the SVC-SP) isValidNfeKey('3517 0458 7165 2300 0119 5500 1000 0000 1210 0012 3458'); // true (masked) isValidNfeKey('3517.0458.7165.2300.0119.5500.1000.0000.1210.0012.3458'); // true (any of the mask characters) isValidNfeKey('35260712ABC34501DE35550010000001231102030403'); // true (alphanumeric CNPJ 12ABC34501DE35) isValidNfeKey('35260712ABC34501DEA5550010000001231102030408'); // false (a letter in position 19, a CNPJ check digit) isValidNfeKey('351 70458716523000119550010000000121000123458'); // false (a separator inside a group of 4) isValidNfeKey('99170458716523000119550010000000121000123458'); // false (invalid cUF) isValidNfeKey('35170458716523000119010010000000121000123450'); // false (invalid mod) isValidNfeKey('35170458716523000119550010000000128000123455'); // false (the NF-e MOC does not assign tpEmis 8) isValidNfeKey('35170458716523000119550010000000121000000003'); // false (cNF 00000000, rule B03-10) ``` Source: [MOC NF-e](https://www.confaz.fazenda.gov.br/legislacao/arquivo-manuais/moc7-visao-geral.pdf), [NF-e schemas](https://dfe-portal.svrs.rs.gov.br/NFE/Documentos), [NT Conjunta 2025.001](https://www.nfe.fazenda.gov.br/portal/exibirArquivo.aspx?conteudo=5ZkvIZt10mQ%3D) (CNPJ alfanumérico) and the MOCs cited in `src/is-valid-nfe-key/is-valid-nfe-key.ts`. ### formatNfeKey Format a DF-e (Documento Fiscal eletrônico) access key into groups of 4 characters separated by spaces, the form the DANFE, DACTE, DAMDFE, DABPE, DANF3E and DANFE-COM print it in. - **Options** (`FormatNfeKeyOptions`): `pad` left pads the value with zeros up to the 44 characters of a complete access key (default `false`). An empty value, or one without digits, gives `''` even with `pad`. - A masked or partial key is grouped as far as its characters go. - The letters of an alphanumeric CNPJ are kept, upper cased, in positions 7 to 18; a letter anywhere else is dropped. - The `NFe`, `CTe`, `MDFe`, `BPe`, `NF3e` and `NFCom` prefixes of the `Id` attribute of the XML are stripped first, as `parseNfeKey` reads them. - A value that is neither a string nor a non-negative safe integer (`-1`, `1.5`, a bigint, an object) gives `''`. - Use `isValidNfeKey` to check a key. ```javascript import { formatNfeKey } from '@brazilian-utils/brazilian-utils'; formatNfeKey('35170458716523000119550010000000121000123458'); // '3517 0458 7165 2300 0119 5500 1000 0000 1210 0012 3458' formatNfeKey('35260712abc34501de35550010000001231102030403'); // '3526 0712 ABC3 4501 DE35 5500 1000 0001 2311 0203 0403' (alphanumeric CNPJ) formatNfeKey('NF3e35170458716523000119550010000000121000123458'); // '3517 0458 7165 2300 0119 5500 1000 0000 1210 0012 3458' (XML Id prefix) formatNfeKey('12345'); // '1234 5' formatNfeKey('12345', { pad: true }); // '0000 0000 0000 0000 0000 0000 0000 0000 0000 0001 2345' ``` ### parseNfeKey Remove the formatting of a DF-e access key (chave de acesso), keep only its characters, and cap the result to 44 characters. - The characters kept are the digits and, in positions 7 to 18, the letters of an alphanumeric CNPJ, upper cased; a letter anywhere else is dropped. - The XML `Id` prefixes (`NFe`, `CTe`, `MDFe`, `BPe`, `NF3e`, `NFCom`) are stripped first. ```javascript import { parseNfeKey } from '@brazilian-utils/brazilian-utils'; parseNfeKey('3517 0458 7165 2300 0119 5500 1000 0000 1210 0012 3458'); // '35170458716523000119550010000000121000123458' parseNfeKey('NFe35170458716523000119550010000000121000123458'); // '35170458716523000119550010000000121000123458' parseNfeKey('3526 0712 abc3 4501 de35 5500 1000 0001 2311 0203 0403'); // '35260712ABC34501DE35550010000001231102030403' (alphanumeric CNPJ) ``` ### getNfeKeyInfo Parse a DF-e access key into its fields. Accepts the same input forms as `isValidNfeKey` and returns `null` when the key is not valid. - Returns an `NfeKeyInfo`: `stateCode`, `year`, `month`, `taxId`, `model` (`NfeKeyModel`), `series`, `number`, `emissionType`, `code` and `checkDigit`. - For NFCom and NF3e (models `'62'` and `'66'`) the result also carries `authorizationSite` and `code` is 7 digits instead of 8. - `taxId` is the 14 characters of positions 7 to 20 as written: a numeric CNPJ, an alphanumeric CNPJ (upper cased), or a CPF left padded with zeros. A `taxId` with a letter is always an alphanumeric CNPJ; a padded CPF and a CNPJ starting with `000` look alike, so check it with `isValidCpf` or `isValidCnpj` when the type matters. ```javascript import { getNfeKeyInfo } from '@brazilian-utils/brazilian-utils'; getNfeKeyInfo('35170458716523000119550010000000121000123458'); // { stateCode: 'SP', year: 2017, month: 4, taxId: '58716523000119', model: '55', // series: 1, number: 12, emissionType: 1, code: '00012345', checkDigit: 8 } getNfeKeyInfo('35170458716523000119620010000000121000123450'); // { stateCode: 'SP', year: 2017, month: 4, taxId: '58716523000119', model: '62', // series: 1, number: 12, emissionType: 1, code: '0012345', checkDigit: 0, authorizationSite: 0 } getNfeKeyInfo('35260712ABC34501DE35550010000001231102030403'); // { stateCode: 'SP', year: 2026, month: 7, taxId: '12ABC34501DE35', model: '55', // series: 1, number: 123, emissionType: 1, code: '10203040', checkDigit: 3 } getNfeKeyInfo('invalid'); // null ``` ## NFS-e key ### isValidNfseKey Check if the access key (chave de acesso) of a national NFS-e, the Nota Fiscal de Serviço eletrônica of the Sistema Nacional NFS-e, is valid. - The key is one block of 50 characters, `Cód.Mun.(7) Amb.Ger.(1) Tipo de Inscrição Federal(1) Inscrição Federal(14) nNFSe(13) AAMM(4) Cód.Num.(9) DV(1)`, all digits except an alphanumeric CNPJ in the Inscrição Federal. - The `NFS` literal the `Id` attribute of `infNFSe` puts in front of the key is stripped, with surrounding whitespace. - The DANFSe prints the key as a single block, so it has no printed mask. The boundaries between its 8 fields accept the mask characters `isValidCpf` reads (whitespace, `.`, `-` or `/`, alone or in a run), while a separator inside a field makes the value invalid. - The municipality code must start with an IBGE UF code; it is not looked up in the IBGE table. - `ambGer` must be `1` (the system of the municipality) or `2` (the Sistema Nacional NFS-e), and the registration type `1` (a CPF, left padded with `000`) or `2` (a CNPJ, numeric or alphanumeric), with a CPF or CNPJ whose own check digits are valid. Letters are accepted in a CNPJ only, and lower case is read as upper case, as `isValidCnpj` with `{ version: 2 }` reads it. - `nNFSe` must not be all zeros and the month must be 01 to 12. - The check digit is a modulus 11 over the first 49 characters, weights 2 to 9 cycling from the right, where a remainder of 0 or 1 gives 0. A letter counts as its ASCII code minus 48 (`A` is 17). No official document states it: the NFS-e technical notes 001 to 009, the Anexo I and the Perguntas e Respostas of 08/09/2026 are silent, and Nota Técnica Conjunta 2025.001, whose ASCII minus 48 rule covers the DF-e key, lists the documents it covers (NF-e, NFC-e, CT-e, CT-e OS, GTV-e, MDF-e, BP-e, BP-e TM, NF3e and NFCom) without the NFS-e. The rule is taken by analogy with that NT and the CNPJ's own check digits. - The letters follow `TSIdNFSe` of the schema bundle of 2026-07-27, in the positions of the Inscrição Federal (10 to 23). The production bundle of 09/02/2026 still types the key `[0-9]{50}`. - The municipal NFS-e models that are not the national standard are out of scope. ```javascript import { isValidNfseKey } from '@brazilian-utils/brazilian-utils'; isValidNfseKey('35503082258716523000119000000000001226011357924683'); // true (CNPJ issuer, SP) isValidNfseKey('NFS35503082258716523000119000000000001226011357924683'); // true (XML Id prefix) isValidNfseKey('43149021100040364478829000000000105725120484407255'); // true (CPF issuer, RS) isValidNfseKey('35503082212ABC34501DE35000000000001226091357924682'); // true (alphanumeric CNPJ issuer) isValidNfseKey('35503082258716523000119000000000001226011357924684'); // false (check digit) isValidNfseKey('3550308 2 2 58716523000119 0000000000012 2601 135792468 3'); // true (separators between the fields) ``` ### parseNfseKey Remove everything but the digits and the letters of an alphanumeric CNPJ from the access key of a national NFS-e, and cap the result to 50 characters. - Letters are upper cased, as `parseCnpj` with `{ version: 2 }` does, and the letters in front of the first digit are dropped, the `NFS` prefix of the XML `Id` attribute included, since the key opens with digits. `isValidNfseKey` checks that the letters left stand in a CNPJ. - That is the form the leiaute stores the key in and the one the DANFSe prints, a single block, which is why there is no `formatNfseKey`. ```javascript import { parseNfseKey } from '@brazilian-utils/brazilian-utils'; parseNfseKey('NFS35503082258716523000119000000000001226011357924683'); // '35503082258716523000119000000000001226011357924683' parseNfseKey('3550308 2 2 58716523000119 0000000000012 2601 135792468 3'); // '35503082258716523000119000000000001226011357924683' parseNfseKey('nfs3550308 2 2 12.abc.345/01de-35 0000000000012 2609 135792468 2'); // '35503082212ABC34501DE35000000000001226091357924682' ``` ### getNfseKeyInfo Parse the access key of a national NFS-e into its fields, as an `NfseKeyInfo`. Accepts the same input forms as `isValidNfseKey`. - Returns `municipalityCode`, `stateCode`, `generatorEnvironment`, `taxIdType`, `taxId`, `number`, `year`, `month`, `code` and `checkDigit`. - `generatorEnvironment` is an `NfseKeyGeneratorEnvironment`: `1` the system of the municipality, `2` the Sistema Nacional NFS-e. - `taxIdType` is an `NfseKeyTaxIdType`, `'cpf'` or `'cnpj'`, and `taxId` is the 11 digit CPF, without the `000` that pads it in the key, or the 14 character CNPJ, numeric or alphanumeric, in upper case. - Returns `null` when the key is not valid. ```javascript import { getNfseKeyInfo } from '@brazilian-utils/brazilian-utils'; getNfseKeyInfo('35503082258716523000119000000000001226011357924683'); // { municipalityCode: '3550308', stateCode: 'SP', generatorEnvironment: 2, taxIdType: 'cnpj', // taxId: '58716523000119', number: 12, year: 2026, month: 1, code: '135792468', checkDigit: 3 } getNfseKeyInfo('43149021100040364478829000000000105725120484407255'); // { municipalityCode: '4314902', stateCode: 'RS', generatorEnvironment: 1, taxIdType: 'cpf', // taxId: '40364478829', number: 1057, year: 2025, month: 12, code: '048440725', checkDigit: 5 } getNfseKeyInfo('35503082212ABC34501DE35000000000001226091357924682'); // { municipalityCode: '3550308', stateCode: 'SP', generatorEnvironment: 2, taxIdType: 'cnpj', // taxId: '12ABC34501DE35', number: 12, year: 2026, month: 9, code: '135792468', checkDigit: 2 } getNfseKeyInfo('invalid'); // null ``` Source: the [technical documentation of the Sistema Nacional NFS-e](https://www.gov.br/nfse/pt-br/biblioteca/documentacao-tecnica/documentacao-atual), whose schema types `TSIdNFSe` and `TSChaveNFSe` and ANEXO I field `NFSe/infNFSe/id` define the layout and the rules E1280 and E1284, the [manual da emissão por decisão administrativa ou judicial](https://www.gov.br/nfse/pt-br/biblioteca/documentacao-tecnica/documentacao-atual/manual-contribuintes-emissor-publico-api-emissao-decisao-administrativa-e-judicial.pdf), which names the modulus 11 check digit, [Nota Técnica SE/CGNFS-e 008](https://www.gov.br/nfse/pt-br/biblioteca/documentacao-tecnica/rtc/nt-008-se-cgnfse-danfse-20260714-v1-02.pdf) (item 2.1.1), which prints the key as a single block, the [schemas updated for the alphanumeric CNPJ](https://www.gov.br/nfse/pt-br/noticias/plataforma-nfs-e-disponibiliza-novas-evolucoes-em-producao-restrita-e-divulga-cronograma-de-implantacao) (the restricted-production bundle v1.01-20260727; the service handles the alphanumeric CNPJ in production since 2026-08-10, while the production bundle of 2026-02-09 is still digits only) and [Nota Técnica Conjunta 2025.001](https://www.nfe.fazenda.gov.br/portal/exibirArquivo.aspx?conteudo=5ZkvIZt10mQ=), whose ASCII minus 48 rule for the NF-e key the check digit borrows. ## SUFRAMA ### isValidSuframa Check if an Inscrição SUFRAMA is valid. It is the registration number the Superintendência da Zona Franca de Manaus gives to companies with tax incentives, carried by the `ISUF` field of the NF-e recipient. - The number is `SS.NNNN.LLD`: sector of activity, sequential number, locality of the SUFRAMA unit and check digit. - Accepts 8 or 9 digits. The MOC only says the sector code "pode começar por '0'"; reading an 8 digit value as one whose sector code lost that zero is this library's inference. - Returns `false` for a sector code of `00` and for a wrong módulo 11 check digit. - The sector and locality codes are not checked against a table, since the manual lists them only as examples. - The rule comes from the NF-e Manual de Orientação do Contribuinte (CONFAZ/ENCAT), not from the SUFRAMA, whose Resolução CAS nº 64/2021, art. 5º, only calls the inscrição "um número de identificação e controle" and gives no layout or check digit. - Whitespace, `.`, `-` and `/` are accepted between the fields, as in `isValidCpf`. Any other character makes the value invalid. ```javascript import { isValidSuframa } from '@brazilian-utils/brazilian-utils'; isValidSuframa('123456789'); // true isValidSuframa('12.3456.789'); // true isValidSuframa('10001018'); // true (same as '010001018') isValidSuframa('123456780'); // false isValidSuframa('001234560'); // false (sector 00) ``` ### formatSuframa Format an Inscrição SUFRAMA. - **Options** (`FormatSuframaOptions`): `pad` left-pads the value with zeros to the full 9 digits before masking (default `false`), which restores the leading zero of an 8 digit value. An empty value, or one without digits, gives `''` even with `pad`. - The mask is progressive, as in the other `format` utilities, so an 8 digit value without `pad` is grouped one position early: use `pad: true` for a value read straight out of the `ISUF` field, which may be stored with 8 digits. ```javascript import { formatSuframa } from '@brazilian-utils/brazilian-utils'; formatSuframa('123456789'); // 12.3456.789 formatSuframa('10001018'); // 10.0010.18 (8 digits, the mask groups one position early) formatSuframa('10001018', { pad: true }); // 01.0001.018 ``` ### parseSuframa Remove Inscrição SUFRAMA formatting, keep only digits, and cap the result to 9 digits. ```javascript import { parseSuframa } from '@brazilian-utils/brazilian-utils'; parseSuframa('12.3456.789'); // 123456789 ``` ### generateSuframa Generate a valid random 9 digit Inscrição SUFRAMA. - The check digit is valid and the sector code is never `00`. The sector and locality codes are random. ```javascript import { generateSuframa } from '@brazilian-utils/brazilian-utils'; generateSuframa(); // '205678106' ``` Source: [NF-e Manual de Orientação do Contribuinte 7.0, Visão Geral](https://www.confaz.fazenda.gov.br/legislacao/arquivo-manuais/moc7-visao-geral.pdf) (section 8.4), [MOC 7.0, Anexo I](https://www.confaz.fazenda.gov.br/legislacao/arquivo-manuais/moc7-anexo-i-leiaute-e-rv.pdf) (field 79, `E18` `ISUF`, and rule E18-20). ## Phone ### isValidPhone Check if a phone number (mobile or landline) is valid. A Brazilian country code (`+55`, `0055` or a bare `55`) is accepted and removed first, as in `parsePhone`. Any character other than digits, whitespace and `()+.-/` (a letter, for instance) makes the value invalid; up to 2.4.0 such characters were dropped. - **Options** (`IsValidPhoneOptions`): `accept` (`PhoneType[]`, default `['mobile', 'landline']`) picks which kinds of number count as valid; add `'service'` for the numbers `isValidServicePhone` recognizes. `version` (`PhoneVersion`, default `1`) is forwarded to `isValidMobilePhone`. - A mobile number must start with 7, 8 or 9 under both versions (Resolução Anatel 749/2022, art. 12, I, "a"), so a leading 6 is rejected; up to 2.4.0 the default version accepted it. ```javascript import { isValidPhone } from '@brazilian-utils/brazilian-utils'; isValidPhone('11900000000'); // true isValidPhone('11712345678', { version: 2 }); // true (7, 8 and 9 are all SMP) isValidPhone('11700123456', { version: 2 }); // false (the 700 series is satellite) isValidPhone('11612345678'); // false (6 is not SMP) isValidPhone('+55 11 98765-4321'); // true (country code accepted) isValidPhone('08001234567'); // false (service numbers rejected by default) isValidPhone('08001234567', { accept: ['service'] }); // true isValidPhone('11900000000', { accept: [] }); // false ``` Source: [Resolução Anatel nº 749/2022](https://informacoes.anatel.gov.br/legislacao/resolucoes/2022/1641-resolucao-749). ### formatPhone Format a phone number according to Brazilian patterns. If `value` includes a DDD, pass `{ mask: 'auto' }` or `'nanp'`: the default `"sn"` mask assumes no DDD and truncates one. - **Options** (`FormatPhoneOptions`): `mask` (`PhoneMask`, default `"sn"`) picks one of the patterns below. An unknown `mask` falls back to `"sn"`. `obfuscate` (default `false`) hides the subscriber number under every mask. - `"sn"`: subscriber number only, 9 digits. `"nanp"`: DDD plus subscriber number, 11 digits for a mobile and 10 for a landline; any other length keeps the 11 digit grouping. - `"e164"` and `"international"` drop the country code first, as `parsePhone` does, and fall back to `"service"` for a service number. `"e164"` keeps at most the 11 national digits, as `"international"` does (up to 2.4.0 it kept them all). - `"sn"` and `"nanp"` drop an explicit `+55` or `0055` too, so `'+5511987654321'` gives `(11) 98765-4321` under `"nanp"` (up to 2.4.0 it gave `(55) 11987-6543`); a bare `55` stays, since it may be the DDD. - A number is read when it is a string or a non-negative safe integer; any other number (negative, fractional, not finite or unsafe) gives an empty string. - Under the `"service"` mask with `obfuscate`, a value that is only a service prefix so far keeps it (`0800` stays `0800`), since the prefix names a service, not a subscriber; a value too short to be recognized (`080`) is fully hidden (`***`). - `"service"`: the Códigos Não Geográficos (`0800 123 4567`) and the abbreviated `300X`/`400X` numbers (`4004-1234`). - `"auto"`: `"service"` for a service number, `"international"` when `value` carries a country code, otherwise `"nanp"` for more than 9 digits, else `"sn"`. - `obfuscate` is a convention of this library, not an official rule: no law, Anatel act or [ANPD guidance](https://www.gov.br/anpd/pt-br/centrais-de-conteudo/documentos-tecnicos-orientativos/estudo_tecnico_sobre_anonimizacao_de_dados_na_lgpd_uma_visao_de_processo_baseado_em_risco_e_tecnicas_computacionais.pdf) sets which digits of a phone number to show ("não há um padrão para o mascaramento"), and the [Banco Central](https://www.bcb.gov.br/content/estabilidadefinanceira/pix/Regulamento_Pix/IV_RequisitosMinimosparaExperienciadoUsuario.pdf) forbids masking a Pix key, a phone number included, when the DICT lookup returns it. - `obfuscate` keeps 2 digits, the count the gov.br account shows for a registered mobile, and keeps the prefix that names a region or a service instead of a subscriber: the DDD, the `0800`-like code and the `300X`/`400X` root. - The 2 digits are the last ones the mask itself has room for, so under the default `"sn"` a DDD-prefixed value is truncated first, exactly as it is without `obfuscate`, and the visible pair is the 8th and 9th digit rather than the last 2 of `value`. - Under the `"service"`, `"auto"`, `"e164"` and `"international"` masks a 3 digit public utility code (`190`) identifies no one and is returned as it is (the other masks read it as an ordinary short number); a value the `"service"` mask does not recognize has every digit replaced by a `*`, which hides the digits but not how many there were. The obfuscated patterns have a fixed number of slots, so under `"e164"` anything past the 11th national digit is dropped. ```javascript import { formatPhone } from '@brazilian-utils/brazilian-utils'; formatPhone('987654321'); // 98765-4321 (default "sn", no DDD) formatPhone('11900000000', { mask: 'nanp' }); // (11) 90000-0000 formatPhone('11900000000', { mask: 'auto' }); // (11) 90000-0000 formatPhone('1130000000', { mask: 'nanp' }); // (11) 3000-0000 (10 digit landline) formatPhone('1130000000', { mask: 'auto' }); // (11) 3000-0000 (10 digit landline) formatPhone('11987654321', { mask: 'e164' }); // +5511987654321 formatPhone('+5511987654321', { mask: 'international' }); // +55 11 98765-4321 formatPhone('+55 11 9', { mask: 'auto' }); // +55 11 9 (typed after +55, the 55 is not read as a DDD) formatPhone('+5511987654321', { mask: 'nanp' }); // (11) 98765-4321 formatPhone('08001234567', { mask: 'service' }); // 0800 123 4567 formatPhone('40041234', { mask: 'service' }); // 4004-1234 formatPhone('+5511987654321', { mask: 'auto' }); // +55 11 98765-4321 ("auto" detects the +55 prefix and picks "international") formatPhone('5508001234567', { mask: 'auto' }); // 0800 123 4567 ("auto" reads the 0800 number, not a +55 08 one) formatPhone('987654321', { obfuscate: true }); // *****-**21 formatPhone('11987654321', { mask: 'auto', obfuscate: true }); // (11) *****-**21 formatPhone('1130000000', { mask: 'auto', obfuscate: true }); // (11) ****-**00 formatPhone('+5511987654321', { mask: 'auto', obfuscate: true }); // +55 11 *****-**21 formatPhone('11987654321', { mask: 'e164', obfuscate: true }); // +5511*******21 formatPhone('08001234567', { mask: 'service', obfuscate: true }); // 0800 *** **67 formatPhone('40041234', { mask: 'service', obfuscate: true }); // 4004-**34 formatPhone('11988887766', { mask: 'service', obfuscate: true }); // *********** (not a service number) formatPhone('11987654321', { obfuscate: true }); // *****-**43 (BEWARE: "sn" truncates first, so "43", not "21") formatPhone('11900000000'); // 11900-0000 (BEWARE: default "sn" truncates a DDD-prefixed number) ``` Source: [ITU-T E.164](https://www.itu.int/rec/T-REC-E.164), [Resolução Anatel nº 749/2022](https://informacoes.anatel.gov.br/legislacao/resolucoes/2022/1641-resolucao-749), [conta gov.br](https://acesso.gov.br/faq/_perguntasdafaq/formarrecuperarconta.html) for how many digits of a mobile stay visible. ### parsePhone Remove phone formatting, keep only digits, and cap the result to 11 digits. - An explicit country code (`+55` or `0055`) is always stripped first, even while the number is still being typed (`+55 11 9` gives `119`; up to 2.4.0 it gave `55119`). A bare `55` is stripped only when 10 or 11 digits are left (DDD plus subscriber number), so area code 55 is not mistaken for it. - Accepts a string or a non-negative safe integer; any other number (negative, fractional, not finite or unsafe) gives an empty string. ```javascript import { parsePhone } from '@brazilian-utils/brazilian-utils'; parsePhone('(11) 90000-0000'); // 11900000000 parsePhone('+55 (11) 98765-4321'); // 11987654321 parsePhone('5511987654321'); // 11987654321 parsePhone('+55 11 9'); // 119 (explicit country code, number still short) parsePhone('55987654321'); // 55987654321 (area code 55, not mistaken for the +55 country code) ``` ### generatePhone Generate a random Brazilian phone number. Accepts `'mobile'`, `'landline'` or `'service'` (`GeneratePhoneType`); when omitted, it generates a mobile or a landline at random, never a service number. - A mobile starts with 9 after the DDD (valid under both `isValidMobilePhone` versions); a landline has 8 digits after the DDD, starting with 2 to 5 (the range that stays valid after Resolução Anatel 777/2025 narrows it on 1 March 2027; up to 2.4.0 a 6 could be drawn); a service number has no DDD. ```javascript import { generatePhone } from '@brazilian-utils/brazilian-utils'; generatePhone(); // '11912345678' or '1131234567' generatePhone('mobile'); // '11912345678' generatePhone('landline'); // '1131234567' generatePhone('service'); // '08001234567' or '40041234' ``` ### isValidMobilePhone Check if a mobile phone number is valid. A Brazilian country code (`+55`, `0055` or a bare `55`) is accepted and removed first, as in `parsePhone`. Any character other than digits, whitespace and `()+.-/` (a letter, for instance) makes the value invalid; up to 2.4.0 such characters were dropped. - **Options** (`IsValidMobilePhoneOptions`): `version` (`PhoneVersion`, default `1`) picks the numbering rule. Both follow Resolução Anatel 749/2022, art. 12, I, "a" (`"7", "8" e "9": Serviço Móvel Pessoal (SMP)`) and accept only a first digit of 7, 8 or 9; `1` also accepts the `700` series, `2` rejects it as satellite (art. 12, II, "a"). - Up to 2.4.0 version `1` also accepted a first digit of 6, which is not SMP. - Scheduled change, not applied yet: Resolução Anatel 777/2025, art. 22, rewrites art. 12 with effect from 1 March 2027. A first digit of `6` becomes SCM (not a mobile), only `8` and `9` stay SMP, the `700` series becomes "SMGS e SMP por Satélite" and any other `7` number becomes reserva técnica. From that date a `version: 2` that follows it will have to accept only `8` and `9`, plus the `700` series as satellite SMP. ```javascript import { isValidMobilePhone } from '@brazilian-utils/brazilian-utils'; isValidMobilePhone('11900000000'); // true isValidMobilePhone('11712345678', { version: 1 }); // true isValidMobilePhone('11712345678', { version: 2 }); // true (7 is SMP as well) isValidMobilePhone('11612345678'); // false (6 is not SMP, under either version) isValidMobilePhone('11700123456'); // true (version 1 keeps the 700 series) isValidMobilePhone('11700123456', { version: 2 }); // false (the 700 series is satellite) ``` Source: [Resolução Anatel nº 749/2022](https://informacoes.anatel.gov.br/legislacao/resolucoes/2022/1641-resolucao-749) and [Resolução Anatel nº 777/2025](https://informacoes.anatel.gov.br/legislacao/resolucoes/2025/2022-resolucao-777), art. 22. ### isValidLandlinePhone Check if a landline phone number is valid. A Brazilian country code (`+55`, `0055` or a bare `55`) is accepted and removed first, as in `parsePhone`. Any character other than digits, whitespace and `()+.-/` (a letter, for instance) makes the value invalid; up to 2.4.0 such characters were dropped. - The number is the DDD plus 8 digits starting with `2` to `6`, the STFC and SCM range of Resolução Anatel 749/2022, art. 11, I, "a". - Scheduled change, not applied yet: from 1 March 2027 Resolução Anatel 777/2025, art. 21, leaves only `2` to `5` to the STFC, and the SCM moves to 9 digit numbers starting with `6`. From that date a landline starting with `6` will have to be rejected. ```javascript import { isValidLandlinePhone } from '@brazilian-utils/brazilian-utils'; isValidLandlinePhone('1130000000'); // true isValidLandlinePhone('+55 11 3000-0000'); // true (country code accepted) ``` Source: [Resolução Anatel nº 749/2022](https://informacoes.anatel.gov.br/legislacao/resolucoes/2022/1641-resolucao-749), art. 11, and [Resolução Anatel nº 777/2025](https://informacoes.anatel.gov.br/legislacao/resolucoes/2025/2022-resolucao-777), art. 21. ### isValidServicePhone Check if a phone number is a valid Brazilian service number, dialed without a DDD. Only the structure is checked: the number does not have to be assigned to anyone. A Brazilian country code (`+55`, `0055` or a bare `55`) is accepted and removed first, as in `isValidPhone` with `accept: ['service']` (up to 2.4.0 `+55 0800 123 4567` was rejected here). Any character other than digits, whitespace and `()+.-/` (a letter, for instance) makes the value invalid; up to 2.4.0 such characters were dropped. - The Códigos Não Geográficos `0300`, `0303`, `0500`, `0800` and `0900` followed by 7 digits (11 in total): the 10 digit series of Resolução Anatel 749/2022, art. 18, dialed behind the `0` prefix (art. 28). - The abbreviated `300X`/`400X` numbers, 8 digits. Other carrier prefixes such as `4020` and `4062` are rejected. - The 3 digit public utility codes Anatel has designated (e.g. `190`, `192`), as listed on the [Anatel SUP page](https://www.gov.br/anatel/pt-br/regulado/numeracao/codigos-nacionais/servicos-de-utilidade-publica-e-de-emergencia) (modified on 22/06/2023) and in the Anexo of Ato 43.151/2004, the last consolidated act. The page lists `112/911` for the Polícia Militar on handsets: `112` is accepted; `911` is rejected, since Resolução 749/2022, art. 13, holds every series outside `1XX` in reserva técnica. Up to 2.4.0 `112` was rejected too. ```javascript import { isValidServicePhone } from '@brazilian-utils/brazilian-utils'; isValidServicePhone('0800 123 4567'); // true isValidServicePhone('4004-1234'); // true isValidServicePhone('190'); // true isValidServicePhone('+55 0800 123 4567'); // true (country code accepted) isValidServicePhone('11987654321'); // false (geographic number) ``` Source: [Resolução Anatel nº 749/2022](https://informacoes.anatel.gov.br/legislacao/resolucoes/2022/1641-resolucao-749), [Anatel SUP page](https://www.gov.br/anatel/pt-br/regulado/numeracao/codigos-nacionais/servicos-de-utilidade-publica-e-de-emergencia), [Ato Anatel nº 43.151/2004](https://informacoes.anatel.gov.br/legislacao/atos-de-numeracao/2004/1648-ato-43151), [Resolução nº 86/1998](https://informacoes.anatel.gov.br/legislacao/resolucoes/1998/336-resolucao-86). ### getAreaCodeByMunicipalityCode Get the DDD (area code) a Brazilian municipality dials, given its 7-digit IBGE code, from the Anatel table of the Códigos Nacionais in force. - Accepts the code the way `getMunicipalityByCode` does: a string (any non-digit characters stripped) or a non-negative integer. - Returns the DDD as a number, or `null` when the code is not a municipality. Every one of the 5,571 municipalities has exactly one DDD. - A DDD mostly follows state lines. The exceptions: 61 also covers 12 municipalities of Goiás around Brasília, and Porto União (SC) dials 42, Rio Negro (PR) 47 and Barracão (PR) 49. ```javascript import { getAreaCodeByMunicipalityCode } from '@brazilian-utils/brazilian-utils'; getAreaCodeByMunicipalityCode('3550308'); // 11 (São Paulo/SP) getAreaCodeByMunicipalityCode(3304557); // 21 (Rio de Janeiro/RJ) getAreaCodeByMunicipalityCode('4122305'); // 47 (Rio Negro/PR) getAreaCodeByMunicipalityCode('0000000'); // null ``` Source: [Resolução Anatel nº 749/2022](https://informacoes.anatel.gov.br/legislacao/resolucoes/2022/1641-resolucao-749), [Anatel Códigos Nacionais](https://www.gov.br/anatel/pt-br/regulado/numeracao/codigos-nacionais), [Anatel table of the Códigos Nacionais by municipality (21/09/2026)](https://informacoes.anatel.gov.br/paineis/areas-tarifarias/codigos-nacionais). ### getAreaCodeInfo Get the state and region a Brazilian DDD (area code) belongs to, out of the 67 DDDs in use under the Anatel Plano Geral de Numeração. Accepts a string or a non-negative integer. - A string has any non-digit characters stripped, so `'(11)'`, `'0xx11'` and `'DDD 11'` are the DDD 11. - Returns an `AreaCodeInfo`: `areaCode`, `stateCode`, `stateName`, `regionCode`, `regionName` and `stateCodes`. Returns `null` when the DDD is not in use. - `stateCode` is the state the DDD is seated in. For the four DDDs that straddle a border (61, 42, 47 and 49) `stateCodes` also lists the other state, the seat first. ```javascript import { getAreaCodeInfo } from '@brazilian-utils/brazilian-utils'; getAreaCodeInfo('11'); // { areaCode: 11, stateCode: 'SP', stateName: 'São Paulo', regionCode: 'SE', regionName: 'Sudeste', stateCodes: ['SP'] } getAreaCodeInfo(21); // { areaCode: 21, stateCode: 'RJ', stateName: 'Rio de Janeiro', regionCode: 'SE', regionName: 'Sudeste', stateCodes: ['RJ'] } getAreaCodeInfo('61'); // { areaCode: 61, stateCode: 'DF', stateName: 'Distrito Federal', regionCode: 'CO', regionName: 'Centro-Oeste', stateCodes: ['DF', 'GO'] } getAreaCodeInfo('00'); // null getAreaCodeInfo('(0xx11)'); // the same as '11' getAreaCodeInfo(-11); // null getAreaCodeInfo(1.1); // null ``` Source: [Resolução Anatel nº 749/2022](https://informacoes.anatel.gov.br/legislacao/resolucoes/2022/1641-resolucao-749), [Anatel Códigos Nacionais](https://www.gov.br/anatel/pt-br/regulado/numeracao/codigos-nacionais), [Anatel table of the Códigos Nacionais by municipality (21/09/2026)](https://informacoes.anatel.gov.br/paineis/areas-tarifarias/codigos-nacionais). ### getAreaCodesByState Get every DDD (area code) that serves a given Brazilian state, under the Anatel Plano Geral de Numeração. The match is case-insensitive and the result is sorted in ascending order. - Returns `[]` when `stateCode` does not match a Brazilian state. - A DDD that straddles a border (the same four as `getAreaCodeInfo`) is listed under every state it serves. ```javascript import { getAreaCodesByState } from '@brazilian-utils/brazilian-utils'; getAreaCodesByState('SP'); // [11, 12, 13, 14, 15, 16, 17, 18, 19] getAreaCodesByState('ac'); // [68] getAreaCodesByState('DF'); // [61] getAreaCodesByState('GO'); // [61, 62, 64] getAreaCodesByState('SC'); // [42, 47, 48, 49] getAreaCodesByState('XX'); // [] ``` Source: [Resolução Anatel nº 749/2022](https://informacoes.anatel.gov.br/legislacao/resolucoes/2022/1641-resolucao-749), [Anatel Códigos Nacionais](https://www.gov.br/anatel/pt-br/regulado/numeracao/codigos-nacionais), [Anatel table of the Códigos Nacionais by municipality (21/09/2026)](https://informacoes.anatel.gov.br/paineis/areas-tarifarias/codigos-nacionais). ### getMunicipalitiesByAreaCode List the Brazilian municipalities that dial a given DDD (area code), from the Anatel table of the Códigos Nacionais in force. - Accepts the DDD the way `getAreaCodeInfo` does: a string (any non-digit characters stripped) or a non-negative integer. - Returns an array of `{ code, name, stateCode }` (`Municipality`): the seat state's municipalities first, then those of the other state the DDD crosses into, each state's sorted by name. Returns `[]` when the DDD is not in use. ```javascript import { getMunicipalitiesByAreaCode } from '@brazilian-utils/brazilian-utils'; getMunicipalitiesByAreaCode(68).length; // 22 (every municipality of Acre) getMunicipalitiesByAreaCode('(61)').length; // 13 (Brasília and 12 municipalities of Goiás) getMunicipalitiesByAreaCode('47').at(-1); // { code: '4122305', name: 'Rio Negro', stateCode: 'PR' } getMunicipalitiesByAreaCode('20'); // [] ``` Source: [Resolução Anatel nº 749/2022](https://informacoes.anatel.gov.br/legislacao/resolucoes/2022/1641-resolucao-749), [Anatel Códigos Nacionais](https://www.gov.br/anatel/pt-br/regulado/numeracao/codigos-nacionais), [Anatel table of the Códigos Nacionais by municipality (21/09/2026)](https://informacoes.anatel.gov.br/paineis/areas-tarifarias/codigos-nacionais). ## License plate ### isValidLicensePlate Check if a license plate is valid. Accepts the old Brazilian format (`ABC-1234`) and the Mercosul format (`ABC1D23`), with or without a mask, in any case. The mask (whitespace, `.`, `-` or `/`, alone or in a run) is accepted only between the third character and the last four; any other character (`@`, an emoji, a separator anywhere else) makes the plate invalid instead of being stripped. The optional `format` of the second argument (`IsValidLicensePlateOptions`) restricts the check to one of them: `"LLLNNNN"` for the old format or `"LLLNLNN"` for the Mercosul one, the names `getFormatLicensePlate` returns. It works like the `type` argument of the Python library's `is_valid`, whose values are named `"old_format"` and `"mercosul"` there. Those names are not formats here: without `format`, or with any other value, a plate in either format is valid. ```javascript import { isValidLicensePlate } from '@brazilian-utils/brazilian-utils'; isValidLicensePlate('ABC1234'); // true (Brazilian format) isValidLicensePlate('ABC-1234'); // true (Brazilian format with hyphen) isValidLicensePlate('ABC 1234'); // true (whitespace mask) isValidLicensePlate('ABC1D23'); // true (Mercosul format) isValidLicensePlate('ABC12D3'); // false (not a Mercosul sequence) isValidLicensePlate('ABC1234EXTRA'); // false (too many characters) isValidLicensePlate('A-BC1234'); // false (the mask sits after the third character only) isValidLicensePlate('ABC1234!'); // false (any other character is rejected) isValidLicensePlate('ABC1D23', { format: 'LLLNLNN' }); // true isValidLicensePlate('ABC1234', { format: 'LLLNLNN' }); // false (an old format plate) isValidLicensePlate('ABC-1234', { format: 'LLLNNNN' }); // true ``` Source: [Resolução CONTRAN nº 969/2022](https://www.gov.br/transportes/pt-br/assuntos/transito/conteudo-contran/resolucoes/resolucao9692022.pdf), [Anexos](https://www.gov.br/transportes/pt-br/assuntos/transito/conteudo-contran/resolucoes/resolucao9692022anexos.pdf). ### formatLicensePlate Format a license plate. Old Brazilian plates (`LLLNNNN`) get a hyphen; Mercosul plates (`LLLNLNN`) are returned without a separator. - Returns `''` when the value cannot start a valid plate. - A partial value is formatted progressively, so the function works as an input mask: the hyphen shows up as soon as the fourth character is a digit, and a fifth character that is a letter keeps the Mercosul form. ```javascript import { formatLicensePlate } from '@brazilian-utils/brazilian-utils'; formatLicensePlate('abc1234'); // 'ABC-1234' formatLicensePlate('abc1d23'); // 'ABC1D23' formatLicensePlate('abc1'); // 'ABC-1' (a partial value is formatted as far as it goes) formatLicensePlate('abc1d'); // 'ABC1D' ``` ### parseLicensePlate Remove separators from a license plate, normalize it to uppercase, and cap it to 7 characters. ```javascript import { parseLicensePlate } from '@brazilian-utils/brazilian-utils'; parseLicensePlate('abc-1234'); // 'ABC1234' ``` ### generateLicensePlate Generate a valid random license plate in the chosen format. - `format` (`GenerateLicensePlateFormat`, an alias of `LicensePlateFormat`): `'LLLNLNN'` (Mercosul, the default) or `'LLLNNNN'` (the old Brazilian format). Any other value falls back to the default. - The letter in the fifth position of a Mercosul plate is drawn from `K` to `Z`: `A` to `J` is used only to convert an old format plate (Anexo II, item 2, of Resolução CONTRAN nº 969/2022), so a new plate never carries it. ```javascript import { generateLicensePlate } from '@brazilian-utils/brazilian-utils'; generateLicensePlate(); // 'ABC1K23' (Mercosul, the default) generateLicensePlate('LLLNNNN'); // 'ABC1234' generateLicensePlate('LLLNNLN'); // 'ABC1K23' (a format outside the two in circulation falls back to the default) ``` Source: [Resolução CONTRAN nº 969/2022](https://www.gov.br/transportes/pt-br/assuntos/transito/conteudo-contran/resolucoes/resolucao9692022.pdf). ### getFormatLicensePlate Detect the normalized format of a license plate: `'LLLNNNN'` for the old Brazilian format, `'LLLNLNN'` for Mercosul. - Returns `null` when the value, separators removed, is not 7 letters and digits in one of the two formats. - Exports the `LicensePlateFormat` type, which `generateLicensePlate` re-exports as `GenerateLicensePlateFormat`. ```javascript import { getFormatLicensePlate } from '@brazilian-utils/brazilian-utils'; getFormatLicensePlate('ABC-1234'); // 'LLLNNNN' getFormatLicensePlate('ABC1D23'); // 'LLLNLNN' getFormatLicensePlate('ABC12D3'); // null (not a Mercosul sequence) getFormatLicensePlate('INVALID'); // null getFormatLicensePlate('ABC1234EXTRA'); // null (too many characters) ``` ### convertLicensePlateToMercosul Convert an old format Brazilian license plate (`LLLNNNN`) to the Mercosul format (`LLLNLNN`). The 5th digit becomes a letter, `0` through `9` mapping to `A` through `J`. - Returns `""` when the value is not a valid old format license plate. ```javascript import { convertLicensePlateToMercosul } from '@brazilian-utils/brazilian-utils'; convertLicensePlateToMercosul('ABC1234'); // 'ABC1C34' convertLicensePlateToMercosul('abc-1234'); // 'ABC1C34' convertLicensePlateToMercosul('ABC1D23'); // '' (already Mercosul) ``` Source: [Resolução CONTRAN nº 969/2022](https://www.gov.br/transportes/pt-br/assuntos/transito/conteudo-contran/resolucoes/resolucao9692022.pdf), [Anexo II](https://www.gov.br/transportes/pt-br/assuntos/transito/conteudo-contran/resolucoes/resolucao9692022anexos.pdf). ## RENAVAM ### isValidRenavam Check if a RENAVAM (Registro Nacional de Veículos Automotores) is valid. Accepts the old format (9 digits) and the new format (11 digits). - Spaces, dots, hyphens and slashes are ignored; any other character makes the value invalid. - A number loses its leading zeros, so an 11 digit RENAVAM that starts with `0` is only accepted as a string: `isValidRenavam('08794266580')` is `true` and `isValidRenavam(8794266580)` is `false`. - The check digit is the one of Portaria DENATRAN nº 27/2013, art. 1º: "10 dígitos e um dígito verificador, calculado através do módulo 11, peso 9", read as the weights 3, 2, 9, 8, 7, 6, 5, 4, 3 and 2. The portaria gives neither the weights one by one nor the handling of a remainder of 0, 1 or 10, which follow [validation-br](https://github.com/klawdyo/validation-br/blob/main/src/renavam.ts) and [brutils](https://github.com/brazilian-utils/python/blob/main/brutils/renavam.py); padding a 9 digit code to 11 with zeros is market practice. ```javascript import { isValidRenavam } from '@brazilian-utils/brazilian-utils'; isValidRenavam('639884962'); // true (9 digits, old format) isValidRenavam('00639884962'); // true (11 digits, new format) isValidRenavam('0063988.4962'); // true (the dot is ignored) isValidRenavam('12345678901'); // false (invalid checksum) isValidRenavam('00000000000'); // false (repeated digits) isValidRenavam('ab00639884962'); // false (letters are rejected) ``` Source: [Portaria DENATRAN nº 27/2013](https://www.gov.br/transportes/pt-br/assuntos/transito/arquivos-senatran/portarias/2013/portaria0272013.pdf). ### generateRenavam Generate a valid random RENAVAM in the 11 digit form: ten base digits plus the check digit. ```javascript import { generateRenavam } from '@brazilian-utils/brazilian-utils'; generateRenavam(); // '12345678900' ``` ## PIS ### isValidPis Check if a PIS is valid. Accepts the value masked or not. - A value whose digits are all the same is rejected. - The check digit uses the weights 3, 2, 9, 8, 7, 6, 5, 4, 3 and 2 and módulo 11. No official document found publishes them: the eSocial and SIRC manuals say only that the number has 11 digits and a módulo 11 check digit, and the Caixa layouts ask for a "Número de PIS/PASEP válido" without saying how it is computed. The weights follow [brutils](https://github.com/brazilian-utils/python/blob/main/brutils/pis.py). ```javascript import { isValidPis } from '@brazilian-utils/brazilian-utils'; isValidPis('12056412847'); // true isValidPis('12056412547'); // false ``` ### formatPis Format a PIS. - **Options** (`FormatPisOptions`): `pad` left-pads the value with zeros to 11 digits before masking (default `false`); `obfuscate` hides the first 3 digits and the check digit. An empty value, or one without digits, gives `''` even with `pad`. - `obfuscate` is applied after `pad`. - No authority publishes a masking rule for the PIS, so `obfuscate` applies the one the Leis de Diretrizes Orçamentárias set for publishing a CPF ("ocultar os três primeiros dígitos e os dois dígitos verificadores", Lei nº 14.194/2021, art. 149, first set by Lei nº 12.309/2010, art. 87, § 5º), a number with the same structure. ```javascript import { formatPis } from '@brazilian-utils/brazilian-utils'; formatPis('12345678901'); // 123.45678.90-1 formatPis('123456789', { pad: true }); // 001.23456.78-9 formatPis('12345678901', { obfuscate: true }); // ***.45678.90-* ``` ### parsePis Remove PIS formatting, keep only digits, and cap the result to 11 digits. ```javascript import { parsePis } from '@brazilian-utils/brazilian-utils'; parsePis('123.45678.90-1'); // 12345678901 ``` ### generatePis Generate a valid random PIS. ```javascript import { generatePis } from '@brazilian-utils/brazilian-utils'; generatePis(); // '91077906857' ``` Source: [Lei nº 14.194/2021, art. 149](https://www.planalto.gov.br/ccivil_03/_ato2019-2022/2021/lei/L14194.htm), the CPF masking rule `obfuscate` borrows, first set by [Lei nº 12.309/2010, art. 87, § 5º](https://www.planalto.gov.br/ccivil_03/_ato2007-2010/2010/lei/l12309.htm) and repeated by the later LDOs ([Lei nº 15.321/2025, art. 163](https://www.planalto.gov.br/ccivil_03/_ato2023-2026/2025/lei/L15321.htm#art163), the one for 2026, repeats it). ## Processo jurídico ### isValidProcessoJuridico Check if a processo jurídico number is valid, per Resolução CNJ nº 65/2008. Three things are checked: the `NNNNNNN-DD.AAAA.J.TR.OOOO` layout, the `DD` check digits (ISO 7064 MOD 97-10) and the `J`/`TR` pair. - `J` and `TR` must name an órgão and a tribunal that exist. - The unidade de origem (`OOOO`) is only checked as four digits. ```javascript import { isValidProcessoJuridico } from '@brazilian-utils/brazilian-utils'; isValidProcessoJuridico('00020802520125150049'); // true isValidProcessoJuridico('0002080-25.2012.5.15.0049'); // true (CNJ mask) isValidProcessoJuridico('0000100-68.2008.4.06.0000'); // true (TRF da 6ª Região) isValidProcessoJuridico('0000100-23.2008.8.28.0000'); // false (no 28th Tribunal de Justiça) isValidProcessoJuridico('ab00020802520125150049'); // false (letters are rejected) ``` Source: [Resolução CNJ nº 65/2008](https://atos.cnj.jus.br/atos/detalhar/119), art. 1º (layout, `J` and `TR`) and Anexo VIII ("CÁLCULO DO DÍGITO VERIFICADOR"); the TRF da 6ª Região (`4.06`) per [Resolução CNJ nº 477/2022](https://atos.cnj.jus.br/atos/detalhar/4781). ### formatProcessoJuridico Format a processo jurídico number in the CNJ mask `NNNNNNN-DD.AAAA.J.TR.OOOO`. - **Options** (`FormatProcessoJuridicoOptions`): `pad` left-pads the value with zeros to 20 digits before masking (default `false`). An empty value, or one without digits, gives `''` even with `pad`. ```javascript import { formatProcessoJuridico } from '@brazilian-utils/brazilian-utils'; formatProcessoJuridico('00020802520125150049'); // '0002080-25.2012.5.15.0049' formatProcessoJuridico('20802520125150049', { pad: true }); // '0002080-25.2012.5.15.0049' ``` Source: [Resolução CNJ nº 65/2008](https://atos.cnj.jus.br/atos/detalhar/119). ### parseProcessoJuridico Remove processo jurídico formatting, keep only digits, and cap the result to 20 digits. ```javascript import { parseProcessoJuridico } from '@brazilian-utils/brazilian-utils'; parseProcessoJuridico('0002080-25.2012.5.15.0049'); // '00020802520125150049' ``` ### generateProcessoJuridico Generate a valid random processo jurídico number in the layout of Resolução CNJ nº 65/2008. - **Options** (`GenerateProcessoJuridicoParams`): `year` sets the `AAAA` field, an integer from the current year to 9999 (default: the current year); `court` sets the órgão `J`, from 1 to 9 (default: random). - `TR` is drawn among the tribunais of the chosen órgão, so the pair always names a court that exists. - Returns `null` when `year` or `court` is out of range. ```javascript import { generateProcessoJuridico } from '@brazilian-utils/brazilian-utils'; generateProcessoJuridico(); // '89478645020266070326' generateProcessoJuridico({ year: 2026, court: 5 }); // '98412562120265087260' (Justiça do Trabalho, TRT da 8ª Região) generateProcessoJuridico({ year: 10000 }); // null (year out of range) generateProcessoJuridico({ court: 10 }); // null (no such órgão) ``` Source: [Resolução CNJ nº 65/2008](https://atos.cnj.jus.br/atos/detalhar/119). ### getProcessoJuridicoInfo Read the fields of a processo jurídico number, as a `ProcessoJuridicoInfo`, or `null` when `isValidProcessoJuridico` would return `false`. - Fields: `sequentialNumber` (`NNNNNNN`), `checkDigits` (`DD`), `year` (`AAAA`, a number), `segment` (a name for the órgão `J`: `'supreme-federal-court'`, `'national-council-of-justice'`, `'superior-court-of-justice'`, `'federal'`, `'labor'`, `'electoral'`, `'military'`, `'state'` or `'state-military'`), `segmentCode` (`J`, `'1'` to `'9'`), `tribunalCode` (`TR`, two digits) and `originUnit` (`OOOO`). Codes are strings that keep their leading zeros. - `tribunalCode` is `'00'` for the processes of a superior court or of the STF, the CNJ, the STJ, the TST, the TSE and the STM, `'90'` for the Conselho da Justiça Federal and the Conselho Superior da Justiça do Trabalho, and the number of the region or state otherwise. The unit of origin is not checked: each tribunal codifies its own. ```javascript import { getProcessoJuridicoInfo } from '@brazilian-utils/brazilian-utils'; getProcessoJuridicoInfo('0002080-25.2012.5.15.0049'); // { // sequentialNumber: '0002080', // checkDigits: '25', // year: 2012, // segment: 'labor', // segmentCode: '5', // tribunalCode: '15', // originUnit: '0049', // } getProcessoJuridicoInfo('0000100-23.2008.8.28.0000'); // null (no 28th Tribunal de Justiça) ``` Source: [Resolução CNJ nº 65/2008](https://atos.cnj.jus.br/atos/detalhar/119). ## Bank accounts and banks ### isValidBankAccount Check if a Brazilian bank account is valid. The `bankCode` must be a Banco Central STR participant (the list `getBankByCode` uses). - **Params** (`IsValidBankAccountParams`, all strings): `bankCode` (3 digits), `agency` (1-5 digits), `account` (1-13 digits) and `digit` (1-2 characters, or `X` for Banco do Brasil and `P` for Bradesco). - A listed bank is validated in one of three ways: by a check digit rule, by structure only, or by a generic mod10/mod11 fallback. - No act of the Banco Central, of another government body or of Febraban sets these check digit rules. Those of banks 001, 033, 041, 104, 237, 341, 399 and 745 come from the "Regras de Validação de dígito verificador de agência e conta corrente" compendium of Icatu Seguros, a private compilation of each bank's rule. Nubank publishes no rule: its Verhoeff digit is the one open source validators derived from real accounts. - Three banks publish their own rule in their layout manuals, and the rules here match them: the [Caixa](https://www.caixa.gov.br/Downloads/cobranca-caixa/Manual_de_Leiaute_de_Arquivo_Eletronico_CNAB_400.pdf) both of its digits over a 12 digit account (notes NE051 and NE052), Santander the account digit ([Débito Automático 150 v08](https://www.santander.com.br/layout-de-arquivos), April 2026), and [Banco do Brasil](https://www.bb.com.br/docs/pub/emp/empl/dwn/Doc5175Bloqueto.pdf) only the agency digit (Anexo XI), its account digit being only "módulo 11". - The only official texts on these digits say there is no common rule: the FEBRABAN [Layout Padrão CNAB 240 v11.0](https://cmsarquivos.febraban.org.br/Arquivos/documentos/PDF/Layout%20padrao%20CNAB240%20V%2011_0%20-%202026_09_11.pdf) (11/09/2026), notes G009, G011 and G012, calls each of them a "código adotado pelo Banco" and gives no algorithm, and the DICT API of the Banco Central takes the account with its digit and computes nothing. Banks validated by a check digit rule: | Bank | Code | Agency | Account | Notes | | --- | --- | --- | --- | --- | | Banco do Brasil | `001` | 4-5 digits | 8-10 digits | mod11 with weights 2..9 cycling from the right; `digit` may be `"X"` | | Santander | `033` | 4 digits | 8 digits | weights `9,7,3,1,0,0,9,7,1,3,1,9,7,3` over agency + `"00"` + account, tens discarded | | Banrisul | `041` | 4 digits | 9 digits | weights `3,2,4,7,6,5,4,3,2`; remainder 0 gives `0` and remainder 1 gives `6`; `account` is tipo (2 digits) + conta (7 digits) | | Caixa Econômica Federal | `104` | 4 digits | 11-12 digits | mod11 with weights 2..9 cycling from the right, a result above 9 giving `0`. A 12 digit `account` (the format of the Caixa layouts, "sem operação") takes either its own digit (over the account) or the agency/account one (over agency + account); an 11 digit one is operação (3 digits) + conta (8 digits), with the digit over agency + account. Up to 2.4.0 a 12 digit account was rejected | | Bradesco | `237` | 4 digits | 7 digits | mod11 with weights 2..7 cycling from the right; remainder 0 gives `0` and remainder 1 gives `"P"` | | Nubank | `260` | 4 digits | 5-13 digits | Verhoeff check digit over the account, leading zeros dropped (no published rule; see above) | | Itaú Unibanco | `341` | 4 digits | 5 digits | mod10 over agency + account | | HSBC / Kirton Bank | `399` | 4 digits | 6 digits | weights `8,9,2,3,4,5,6,7,8,9` over agency + account; remainder 10 gives `0` | | Citibank | `745` | 4 digits | 10 digits | weights `11..2` over the account; remainder 0 or 1 gives `0` | Banks validated by structure only, since no check digit rule of theirs is known (a single numeric `digit` is enough): | Bank | Code | | Bank | Code | | --- | --- | --- | --- | --- | | Inter | `077` | | Mercado Pago | `323` | | Ailos | `085` | | C6 | `336` | | XP | `102` | | PicPay | `380` | | Unicred | `136` | | Cora | `403` | | Stone | `197` | | Pan | `623` | | BTG Pactual | `208` | | BV | `655` | | Original | `212` | | Daycoval | `707` | | PagBank | `290` | | Sicredi | `748` | | BMG | `318` | | Sicoob | `756` | - Every other listed bank uses the generic fallback: `digit` must match mod10 or mod11 over the account. A 2 character `digit` chains mod10 then mod11. No published rule backs it and up to three of the ten digits pass for a given account, so `true` for a bank outside the tables above says the structure is plausible, not that the check digit is proven. - For Banco do Brasil the agency digit is not checked: a 5 digit agency (`1584-9`) is only held to the length, whatever its last digit is. ```javascript import { isValidBankAccount } from '@brazilian-utils/brazilian-utils'; isValidBankAccount({ bankCode: '001', agency: '1584', account: '00210169', digit: '6' }); // true (Banco do Brasil) isValidBankAccount({ bankCode: '341', agency: '2545', account: '02366', digit: '1' }); // true (Itaú) isValidBankAccount({ bankCode: '104', agency: '0647', account: '00188888888', digit: '7' }); // true (Caixa: operação "001" + conta "88888888") isValidBankAccount({ bankCode: '041', agency: '2664', account: '358507670', digit: '6' }); // true (Banrisul: tipo "35" + conta "8507670") isValidBankAccount({ bankCode: '260', agency: '0001', account: '5216125', digit: '0' }); // true (Nubank, Verhoeff) isValidBankAccount({ bankCode: '077', agency: '0001', account: '123456789', digit: '0' }); // true (Banco Inter, structure only) isValidBankAccount({ bankCode: '077', agency: '0001', account: '123456789', digit: 'X' }); // false (a structure only bank still requires a numeric digit) isValidBankAccount({ bankCode: '999', agency: '1234', account: '123456', digit: '6' }); // false (999 is not a Banco Central participant) isValidBankAccount({ bankCode: '246', agency: '1234', account: '123456', digit: '6' }); // true (Banco ABC Brasil, generic mod10 fallback) ``` Source: [STR participants list](https://www.bcb.gov.br/content/estabilidadefinanceira/str1/ParticipantesSTR.csv) (official). Based on: the Icatu Seguros compendium [Regras de Validação de dígito verificador de agência e conta corrente](https://github.com/eduardokum/laravel-boleto/blob/master/manuais/Regras%20Validacao%20Conta%20Corrente%20VI_EPS.pdf) and, for Nubank, [bran_checker](https://github.com/Xerpa/bran_checker/tree/master/lib/banks). ### getBanks Get every Brazilian bank with a compensation code (COMPE), from the Banco Central do Brasil STR participants list. - Each bank (`Bank`) has a `code` (COMPE, 3 digits), an `ispb` (8 digits) and a `name`. ```javascript import { getBanks } from '@brazilian-utils/brazilian-utils'; getBanks(); // [ // { code: '001', ispb: '00000000', name: 'Banco do Brasil S.A.' }, // { code: '003', ispb: '04902979', name: 'BANCO DA AMAZONIA S.A.' }, // { code: '004', ispb: '07237373', name: 'Banco do Nordeste do Brasil S.A.' }, // ... 460 more items // ] ``` Source: [STR participants list](https://www.bcb.gov.br/content/estabilidadefinanceira/str1/ParticipantesSTR.csv). ### getBankByCode Look a Brazilian bank up by its compensation code (COMPE), from the Banco Central do Brasil STR participants list. Accepts a `string` or a `number`. - A string has any non-digit characters stripped before the code is padded to 3 digits. - Returns the matching `Bank`, or `null` when no bank has that code. ```javascript import { getBankByCode } from '@brazilian-utils/brazilian-utils'; getBankByCode('001'); // { code: '001', ispb: '00000000', name: 'Banco do Brasil S.A.' } getBankByCode(1); // { code: '001', ispb: '00000000', name: 'Banco do Brasil S.A.' } getBankByCode('999'); // null ``` Source: [STR participants list](https://www.bcb.gov.br/content/estabilidadefinanceira/str1/ParticipantesSTR.csv). ### getBankByIspb Look a Brazilian bank up by its ISPB (Identificador do Sistema de Pagamentos Brasileiro), the 8 character code of every SPB participant. Accepts a `string` or a `number`, with or without leading zeros. - Since Resolução BCB nº 585/2026 an ISPB may hold letters, so a string of 8 letters and digits is looked up as it is, in upper or lower case. Any character that is neither a letter nor a digit is ignored (`'00.000.000'` is `'00000000'`), and a letter is never stripped (`'0000000A'` is not `'00000000'`). - Returns the matching `Bank`, or `null` when no bank has that ISPB. The base only carries institutions that also have a COMPE code. ```javascript import { getBankByIspb } from '@brazilian-utils/brazilian-utils'; getBankByIspb('00000000'); // { code: '001', ispb: '00000000', name: 'Banco do Brasil S.A.' } getBankByIspb('60701190'); // { code: '341', ispb: '60701190', name: 'ITAÚ UNIBANCO S.A.' } getBankByIspb('99999999'); // null ``` Source: [STR participants list](https://www.bcb.gov.br/content/estabilidadefinanceira/str1/ParticipantesSTR.csv), [BrasilAPI](https://brasilapi.com.br/api/banks/v1). ## IBAN ### isValidIban Check if a Brazilian IBAN (International Bank Account Number) is valid. Only Brazilian IBANs (country code `BR`) are recognized; any other country returns `false`. - Layout, 29 characters (Resolução BCB 585/2026, art. 2º, which revoked Circular BCB 3.625/2013 and kept its layout): `BR`, 2 check digits (ISO 7064 MOD 97-10), 8 character ISPB, 5 digit branch, 10 digit account, 1 letter account type, 1 owner indicator. - The ISPB may hold letters: the Resolução makes it "oito caracteres alfanuméricos", where the Circular said "numéricos". Up to 2.4.0 only digits were accepted. - Account type: any letter, usually `C` or `P`. Owner: `1` to `9`, then `A` to `Z`. - Accepts the compact form or groups of 4 split by one whitespace, `.`, `-` or `/`, in any case. ```javascript import { isValidIban } from '@brazilian-utils/brazilian-utils'; isValidIban('BR1500000000000010932840814P2'); // true isValidIban('BR15 0000 0000 0000 1093 2840 814P 2'); // true (grouping spaces) isValidIban('BR15-0000-0000-0000-1093-2840-814P-2'); // true (any of the mask characters) isValidIban('BR1012AB34CD000010932840814P2'); // true (alphanumeric ISPB) isValidIban('BR1500000000000010932840814P3'); // false (bad check digits) isValidIban('BR15 000 00000 0000 1093 2840 814P 2'); // false (a separator inside a group) isValidIban('DE89370400440532013000'); // false (non Brazilian IBAN) ``` Source: [Diretrizes de Implementação do IBAN no Brasil](https://www.bcb.gov.br/content/estabilidadefinanceira/Documents/sistema_pagamentos_brasileiro/IBAN-Guidelines_%20port.pdf), [Resolução BCB nº 585/2026](https://www.bcb.gov.br/estabilidadefinanceira/exibenormativo?tipo=Resolu%C3%A7%C3%A3o%20BCB&numero=585), which revoked [Circular BCB nº 3.625/2013](https://www.bcb.gov.br/pre/normativos/circ/2013/pdf/circ_3625_v1_O.pdf), [ISO 13616-1:2020](https://www.iso.org/standard/81090.html). ### formatIban Format an IBAN in the ISO 13616 print grouping: blocks of 4 characters, the presentation used on statements and bank forms. Does not validate; use `isValidIban` for that. - Caps the result at 29 characters, the length of a Brazilian IBAN. ```javascript import { formatIban } from '@brazilian-utils/brazilian-utils'; formatIban('BR1500000000000010932840814P2'); // 'BR15 0000 0000 0000 1093 2840 814P 2' formatIban('br1500000000000010932840814p2'); // 'BR15 0000 0000 0000 1093 2840 814P 2' formatIban('BR15'); // 'BR15' formatIban('BR15 0000-0000.0000/1093 2840 814P-2'); // 'BR15 0000 0000 0000 1093 2840 814P 2' (only letters and digits are read) ``` Source: [Diretrizes de Implementação do IBAN no Brasil](https://www.bcb.gov.br/content/estabilidadefinanceira/Documents/sistema_pagamentos_brasileiro/IBAN-Guidelines_%20port.pdf), [Resolução BCB nº 585/2026](https://www.bcb.gov.br/estabilidadefinanceira/exibenormativo?tipo=Resolu%C3%A7%C3%A3o%20BCB&numero=585), which revoked [Circular BCB nº 3.625/2013](https://www.bcb.gov.br/pre/normativos/circ/2013/pdf/circ_3625_v1_O.pdf), [ISO 13616-1:2020](https://www.iso.org/standard/81090.html). ### parseIban Remove IBAN formatting, keep the letters and digits, uppercase the result, and cap it to the 29 characters of a Brazilian IBAN. ```javascript import { parseIban } from '@brazilian-utils/brazilian-utils'; parseIban('BR15 0000 0000 0000 1093 2840 814P 2'); // 'BR1500000000000010932840814P2' parseIban('br15-0000.0000/0000 1093 2840 814p-2'); // 'BR1500000000000010932840814P2' ``` Source: [Diretrizes de Implementação do IBAN no Brasil](https://www.bcb.gov.br/content/estabilidadefinanceira/Documents/sistema_pagamentos_brasileiro/IBAN-Guidelines_%20port.pdf), [Resolução BCB nº 585/2026](https://www.bcb.gov.br/estabilidadefinanceira/exibenormativo?tipo=Resolu%C3%A7%C3%A3o%20BCB&numero=585), which revoked [Circular BCB nº 3.625/2013](https://www.bcb.gov.br/pre/normativos/circ/2013/pdf/circ_3625_v1_O.pdf), [ISO 13616-1:2020](https://www.iso.org/standard/81090.html). ### getIbanInfo Parse a Brazilian IBAN into its fields. Returns an `IbanInfo` object, or `null` whenever `isValidIban` would return `false`. - Fields, all strings: `countryCode`, `checkDigits`, `bankIspb`, `branch`, `account`, `accountType` (usually `C` or `P`) and `owner` (`1` to `9`, then `A` to `Z`). - Same input rules as `isValidIban`. ```javascript import { getIbanInfo } from '@brazilian-utils/brazilian-utils'; getIbanInfo('BR1500000000000010932840814P2'); // { // countryCode: 'BR', // checkDigits: '15', // bankIspb: '00000000', // branch: '00001', // account: '0932840814', // accountType: 'P', // owner: '2' // } getIbanInfo('DE89370400440532013000'); // null (non Brazilian IBAN) getIbanInfo('BR15 000 00000 0000 1093 2840 814P 2'); // null (a separator inside a group) ``` Source: [Diretrizes de Implementação do IBAN no Brasil](https://www.bcb.gov.br/content/estabilidadefinanceira/Documents/sistema_pagamentos_brasileiro/IBAN-Guidelines_%20port.pdf), [Resolução BCB nº 585/2026](https://www.bcb.gov.br/estabilidadefinanceira/exibenormativo?tipo=Resolu%C3%A7%C3%A3o%20BCB&numero=585), which revoked [Circular BCB nº 3.625/2013](https://www.bcb.gov.br/pre/normativos/circ/2013/pdf/circ_3625_v1_O.pdf), [ISO 13616-1:2020](https://www.iso.org/standard/81090.html). ## Currency, numbers and dates in words ### formatCurrency Format a number or a numeric string in the BRL pattern (`1.234,56`). A `number` is formatted as is, sign and decimals preserved. - **Options** (`FormatCurrencyOptions`): `symbol` (default `false`) prefixes the result with `R$`; `precision` (default 2) sets the decimal places, clamped to 0 to 20. - A `string` is read as `parseCurrency` reads it, except that a value without any separator stays in whole units: `'1234'` formats as `1.234,00`. - Returns `''` for a non-finite value or one that cannot be coerced to a number. A string is read by `parseCurrency`, so a string with no digit reads as `0` and formats as `0,00` (`'abc'`), and `null` also gives `0,00`. ```javascript import { formatCurrency } from '@brazilian-utils/brazilian-utils'; formatCurrency(10); // 10,00 formatCurrency(10756.11); // 10.756,11 formatCurrency(10756.123, { precision: 3 }); // 10.756,123 formatCurrency(1234.56, { symbol: true }); // R$ 1.234,56 formatCurrency(-1050); // -1.050,00 (a number's sign is preserved) formatCurrency('123456'); // 123.456,00 (a plain digit string is read as a whole number) formatCurrency('1.234,56'); // 1.234,56 (the last "," or "." followed by 1 to 2 digits is the decimal separator) formatCurrency('-10.5'); // -10,50 (a leading "-" is preserved) formatCurrency(Number.NaN); // "" (non finite numbers format as an empty string) ``` Source: [Lei nº 9.069/1995, art. 1º](https://www.planalto.gov.br/ccivil_03/leis/l9069.htm), which sets the `R$` symbol and the comma before the centavos. Based on: the [CLDR](https://cldr.unicode.org/) pt-BR locale data behind `Intl.NumberFormat`, for the `.` grouping. ### parseCurrency Parse a BRL currency string into a number. - **Options** (`ParseCurrencyOptions`): `precision` (default 2) is the number of digits read as minor units, clamped to 0 to 20. - The last `,` or `.` followed by 1 to 2 digits (up to `precision`, when larger) is the decimal separator; every other `,` or `.` is a thousands separator. - A value without any separator is read as cents and divided by `10 ** precision`. - Only a `-` before the first digit makes the result negative: `'(R$ 1,00)'` and `'1,00-'` parse to `1`, and characters that are not digits or separators are dropped, so `'1e5'` parses to `0.15`. ```javascript import { parseCurrency } from '@brazilian-utils/brazilian-utils'; parseCurrency('R$ 1.234,56'); // 1234.56 parseCurrency('1234,56'); // 1234.56 parseCurrency('R$ 0,50'); // 0.5 parseCurrency('R$ 1.234'); // 1234 ("." followed by 3 digits is a thousands separator) parseCurrency('1,5'); // 1.5 parseCurrency('1234'); // 12.34 (no separator at all keeps the cents convention) parseCurrency('-R$ 1,00'); // -1 (a leading "-" is preserved) parseCurrency('R$ 1,001', { precision: 3 }); // 1.001 parseCurrency(''); // 0 ``` Source: [Lei nº 9.069/1995, art. 1º](https://www.planalto.gov.br/ccivil_03/leis/l9069.htm), which sets the `R$` symbol and the comma before the centavos. Based on: the [CLDR](https://cldr.unicode.org/) pt-BR locale data behind `Intl.NumberFormat`, for the `.` grouping. ### convertNumberToWords Write an integer in Brazilian Portuguese cardinal words ("por extenso"): `1235` becomes `"mil duzentos e trinta e cinco"`. - **Options** (`ConvertNumberToWordsOptions`): `gender` (default `"masculine"`) agrees "um/dois" and the hundreds ("duzentos/duzentas") with the noun the number qualifies. - Accepts integers from `-999999999999999` to `999999999999999` (999 trillion). A non-integer is truncated toward zero. - Returns `""` for a value outside that range or not finite. - The last group takes an "e" before it only when it is below 100 or a round hundred: `1200` is `"mil e duzentos"` and `1100` is `"mil e cem"`, while `1235` is `"mil duzentos e trinta e cinco"` and `1101` is `"mil cento e um"`. ```javascript import { convertNumberToWords } from '@brazilian-utils/brazilian-utils'; convertNumberToWords(123); // "cento e vinte e três" convertNumberToWords(1001); // "mil e um" convertNumberToWords(2000000); // "dois milhões" convertNumberToWords(-42); // "menos quarenta e dois" convertNumberToWords(2, { gender: 'feminine' }); // "duas" convertNumberToWords(12.9); // "doze" (truncated toward zero) convertNumberToWords(NaN); // "" ``` ### convertCurrencyToWords Write an amount in reais in words ("por extenso"), as on cheques and contracts: `1523.45` becomes `"mil quinhentos e vinte e três reais e quarenta e cinco centavos"`. Takes no options. - `value` is truncated (not rounded) to 2 decimal places. - Returns `""` for invalid input or an amount above 999 trillion reais. - The singular is used for exactly one (`"um real"`, `"um centavo"`), and a round million, billion or trillion of reais takes "de": `"um milhão de reais"`. - An amount that truncates to nothing is `"zero reais"`, even when negative (`-0.001`); any other negative amount is prefixed with `"menos"`. - Above about 90 trillion reais (`Number.MAX_SAFE_INTEGER / 100`) a number cannot hold cents, so the amount is read as whole reais. ```javascript import { convertCurrencyToWords } from '@brazilian-utils/brazilian-utils'; convertCurrencyToWords(1523.45); // "mil quinhentos e vinte e três reais e quarenta e cinco centavos" convertCurrencyToWords(1); // "um real" convertCurrencyToWords(0.01); // "um centavo" convertCurrencyToWords(1000000); // "um milhão de reais" convertCurrencyToWords(0); // "zero reais" convertCurrencyToWords(-5.5); // "menos cinco reais e cinquenta centavos" convertCurrencyToWords(-0.001); // "zero reais" (truncates to nothing) ``` ### convertDateToWords Write a date in Brazilian Portuguese words ("por extenso"): `"01/01/2024"` becomes `"primeiro de janeiro de dois mil e vinte e quatro"`. Accepts a `Date`, read by its local calendar date, or a string in `"dd/mm/yyyy"` or ISO `"yyyy-mm-dd"` format. - **Options** (`ConvertDateToWordsOptions`): `style` (default `"full"`) spells out day, month and year; `"month"` spells out only the month and leaves day and year as digits, day 1 as `"1º"`. `weekday` (default `false`) prefixes the lowercase weekday name and a comma. - Returns `""` for an invalid `Date`, a malformed string, a day or month that does not exist, or a date before year 1. ```javascript import { convertDateToWords } from '@brazilian-utils/brazilian-utils'; convertDateToWords('01/01/2024'); // "primeiro de janeiro de dois mil e vinte e quatro" convertDateToWords('2024-01-02'); // "dois de janeiro de dois mil e vinte e quatro" convertDateToWords(new Date(2024, 0, 1)); // "primeiro de janeiro de dois mil e vinte e quatro" convertDateToWords('02/03/2024', { style: 'month' }); // "2 de março de 2024" convertDateToWords('01/01/2024', { style: 'month' }); // "1º de janeiro de 2024" convertDateToWords('02/03/2024', { weekday: true }); // "sábado, dois de março de dois mil e vinte e quatro" convertDateToWords('10/05/1999'); // "dez de maio de mil novecentos e noventa e nove" convertDateToWords('31/04/2024'); // "" (April has 30 days) convertDateToWords('invalid'); // "" convertDateToWords('29/02/1900'); // "" (1900 is not a leap year) ``` ## States and municipalities ### getStates Get all Brazilian states, each with its two-letter code, name, region code, region name and 2-digit IBGE code (`cUF`). - Sorted by name in the "pt-BR" locale. - Exports the `State`, `StateCode` and `StateName` types. `State` is a discriminated union: narrowing it by `code` also narrows the other fields. ```javascript import { getStates } from '@brazilian-utils/brazilian-utils'; getStates(); // [ // { code: 'AC', name: 'Acre', regionCode: 'N', regionName: 'Norte', ibgeCode: 12 }, // { code: 'AL', name: 'Alagoas', regionCode: 'NE', regionName: 'Nordeste', ibgeCode: 27 }, // { code: 'AP', name: 'Amapá', regionCode: 'N', regionName: 'Norte', ibgeCode: 16 }, // { code: 'AM', name: 'Amazonas', regionCode: 'N', regionName: 'Norte', ibgeCode: 13 }, // { code: 'BA', name: 'Bahia', regionCode: 'NE', regionName: 'Nordeste', ibgeCode: 29 }, // { code: 'CE', name: 'Ceará', regionCode: 'NE', regionName: 'Nordeste', ibgeCode: 23 }, // { code: 'DF', name: 'Distrito Federal', regionCode: 'CO', regionName: 'Centro-Oeste', ibgeCode: 53 }, // { code: 'ES', name: 'Espírito Santo', regionCode: 'SE', regionName: 'Sudeste', ibgeCode: 32 }, // { code: 'GO', name: 'Goiás', regionCode: 'CO', regionName: 'Centro-Oeste', ibgeCode: 52 }, // { code: 'MA', name: 'Maranhão', regionCode: 'NE', regionName: 'Nordeste', ibgeCode: 21 }, // { code: 'MT', name: 'Mato Grosso', regionCode: 'CO', regionName: 'Centro-Oeste', ibgeCode: 51 }, // { code: 'MS', name: 'Mato Grosso do Sul', regionCode: 'CO', regionName: 'Centro-Oeste', ibgeCode: 50 }, // { code: 'MG', name: 'Minas Gerais', regionCode: 'SE', regionName: 'Sudeste', ibgeCode: 31 }, // { code: 'PA', name: 'Pará', regionCode: 'N', regionName: 'Norte', ibgeCode: 15 }, // { code: 'PB', name: 'Paraíba', regionCode: 'NE', regionName: 'Nordeste', ibgeCode: 25 }, // { code: 'PR', name: 'Paraná', regionCode: 'S', regionName: 'Sul', ibgeCode: 41 }, // { code: 'PE', name: 'Pernambuco', regionCode: 'NE', regionName: 'Nordeste', ibgeCode: 26 }, // { code: 'PI', name: 'Piauí', regionCode: 'NE', regionName: 'Nordeste', ibgeCode: 22 }, // { code: 'RJ', name: 'Rio de Janeiro', regionCode: 'SE', regionName: 'Sudeste', ibgeCode: 33 }, // { code: 'RN', name: 'Rio Grande do Norte', regionCode: 'NE', regionName: 'Nordeste', ibgeCode: 24 }, // { code: 'RS', name: 'Rio Grande do Sul', regionCode: 'S', regionName: 'Sul', ibgeCode: 43 }, // { code: 'RO', name: 'Rondônia', regionCode: 'N', regionName: 'Norte', ibgeCode: 11 }, // { code: 'RR', name: 'Roraima', regionCode: 'N', regionName: 'Norte', ibgeCode: 14 }, // { code: 'SC', name: 'Santa Catarina', regionCode: 'S', regionName: 'Sul', ibgeCode: 42 }, // { code: 'SP', name: 'São Paulo', regionCode: 'SE', regionName: 'Sudeste', ibgeCode: 35 }, // { code: 'SE', name: 'Sergipe', regionCode: 'NE', regionName: 'Nordeste', ibgeCode: 28 }, // { code: 'TO', name: 'Tocantins', regionCode: 'N', regionName: 'Norte', ibgeCode: 17 }, // ] ``` Source: [IBGE Localidades](https://servicodados.ibge.gov.br/api/docs/localidades) ### getStateByCep Get the Brazilian state a CEP belongs to, from the CEP ranges the Correios assign to each state (the "Faixa de CEP" of each UF). - It runs offline: no CEP API is called, so the answer says which state owns the range, not whether the CEP is in use. - Accepts what `isValidCep` accepts: 8 digits, as a string or a number, with spaces, dots, hyphens and slashes ignored. A CEP that starts with `0` has to be a string, and a negative or fractional number is rejected. `getAddressInfoByCep` and `formatCep` with `pad: true` left-pad numbers instead (`1310100` is `01310-100`). - Amazonas, Distrito Federal and Goiás have two ranges each, and no state range covers `00000-000` to `00999-999` nor `78900-000` to `78999-999`. - A range is the block the state owns, not a promise that every CEP in it is in use: `10000-000` sits unused inside the São Paulo range and still answers São Paulo. - Returns `null` for an invalid CEP or one outside every range. Exports the `State` type. ```javascript import { getStateByCep } from '@brazilian-utils/brazilian-utils'; getStateByCep('01310-100'); // { code: 'SP', name: 'São Paulo', regionCode: 'SE', regionName: 'Sudeste', ibgeCode: 35 } getStateByCep(20040020); // { code: 'RJ', name: 'Rio de Janeiro', regionCode: 'SE', regionName: 'Sudeste', ibgeCode: 33 } getStateByCep('69300-000')?.code; // 'RR' getStateByCep('72800-000')?.code; // 'GO' getStateByCep('00999-999'); // null getStateByCep('12345'); // null ``` Source: [Correios, Busca Faixa de CEP](https://buscacepinter.correios.com.br/app/faixa_cep_uf_localidade/index.php) ### getStateByIbgeCode Get the Brazilian state whose 2-digit IBGE code (`cUF`, the Código da Unidade da Federação) matches the given value. - This is the UF code in the first field of a DF-e access key (chave de acesso), the one `isValidNfeKey` covers. - Accepts a string or a non-negative integer, with any non-digit characters of a string stripped (`'35/SP'` is `35`). - Returns `null` when the code matches no state. Exports the `State` type. ```javascript import { getStateByIbgeCode } from '@brazilian-utils/brazilian-utils'; getStateByIbgeCode('35'); // { code: 'SP', name: 'São Paulo', regionCode: 'SE', regionName: 'Sudeste', ibgeCode: 35 } getStateByIbgeCode(11); // { code: 'RO', name: 'Rondônia', regionCode: 'N', regionName: 'Norte', ibgeCode: 11 } getStateByIbgeCode('00'); // null getStateByIbgeCode(-35); // null getStateByIbgeCode(3.5); // null ``` Source: [IBGE Localidades](https://servicodados.ibge.gov.br/api/v1/localidades/estados), [Manual de Orientação do Contribuinte](https://www.confaz.fazenda.gov.br/legislacao/arquivo-manuais/moc7-visao-geral.pdf) ### getStateCodeByName Get the two-letter code (sigla) of a Brazilian state from its full name. - The match ignores accents, case and surrounding whitespace; internal whitespace collapses into one space. - Returns `null` when no state matches. Exports the `StateCode` type. ```javascript import { getStateCodeByName } from '@brazilian-utils/brazilian-utils'; getStateCodeByName('São Paulo'); // 'SP' getStateCodeByName('sao paulo'); // 'SP' getStateCodeByName(' Rio de Janeiro '); // 'RJ' getStateCodeByName('Neverland'); // null ``` Source: [IBGE, API de Localidades, `estados`](https://servicodados.ibge.gov.br/api/v1/localidades/estados) ### getStateNameByCode Get the full name of a Brazilian state from its two-letter code (sigla). - The match ignores case and surrounding whitespace. - Returns `null` when no state matches. Exports the `StateName` type. ```javascript import { getStateNameByCode } from '@brazilian-utils/brazilian-utils'; getStateNameByCode('SP'); // 'São Paulo' getStateNameByCode('sp'); // 'São Paulo' getStateNameByCode(' Rj '); // 'Rio de Janeiro' getStateNameByCode('ZZ'); // null ``` Source: [IBGE, API de Localidades, `estados`](https://servicodados.ibge.gov.br/api/v1/localidades/estados) ### getStateCapital Get the capital of a Brazilian state, as the same `{ code, name, stateCode }` (`Municipality`) that `getMunicipalityByCode` returns for it. - The match ignores case and surrounding whitespace. Returns `null` when no state matches. - The Distrito Federal is not divided into municipalities, but the IBGE codes it as a single one, Brasília, and that is its capital. ```javascript import { getStateCapital } from '@brazilian-utils/brazilian-utils'; getStateCapital('SP'); // { code: '3550308', name: 'São Paulo', stateCode: 'SP' } getStateCapital('to'); // { code: '1721000', name: 'Palmas', stateCode: 'TO' } getStateCapital('DF'); // { code: '5300108', name: 'Brasília', stateCode: 'DF' } getStateCapital('ZZ'); // null ``` Source: [IBGE, Anuário Estatístico do Brasil, table 1.1.1.2 (state capitals, 2025)](https://anuario.ibge.gov.br/2024/territorio/posicao-e-extensao.html) ### getRegions Get the five Brazilian regions (Grandes Regiões), each with its code (the same `regionCode` every state carries), name and IBGE identifier, in the order of that identifier. Exports the `Region` and `RegionCode` types. ```javascript import { getRegions } from '@brazilian-utils/brazilian-utils'; getRegions(); // [ // { code: 'N', name: 'Norte', ibgeCode: 1 }, // { code: 'NE', name: 'Nordeste', ibgeCode: 2 }, // { code: 'SE', name: 'Sudeste', ibgeCode: 3 }, // { code: 'S', name: 'Sul', ibgeCode: 4 }, // { code: 'CO', name: 'Centro-Oeste', ibgeCode: 5 }, // ] ``` Source: [IBGE, API de Localidades, `regioes`](https://servicodados.ibge.gov.br/api/v1/localidades/regioes). ### getStatesByRegion Get the states of a region, given its code (`'N'`, `'NE'`, `'SE'`, `'S'` or `'CO'`), sorted by name the way `getStates` sorts them. - The match ignores case and surrounding whitespace. Returns `[]` when no region matches. ```javascript import { getStatesByRegion } from '@brazilian-utils/brazilian-utils'; getStatesByRegion('S').map((state) => state.code); // ['PR', 'RS', 'SC'] getStatesByRegion('co').map((state) => state.code); // ['DF', 'GO', 'MT', 'MS'] getStatesByRegion('X'); // [] ``` Source: [IBGE, API de Localidades, `estados`](https://servicodados.ibge.gov.br/api/v1/localidades/estados). ### getTimezoneByState Get the IANA time zone name (tzdata zone) of a Brazilian state: the zone of its capital. - Some states straddle more than one zone, and the capital's zone says nothing about the rest: the west of Amazonas (`America/Eirunepe`, UTC-5) and the west of Pará (`America/Santarem`, UTC-3) are not represented, and Fernando de Noronha (`America/Noronha`, UTC-2), a district of Pernambuco, resolves as Recife (UTC-3). The offsets follow the capitals: Acre UTC-5; Amazonas, Roraima, Rondônia, Mato Grosso and Mato Grosso do Sul UTC-4; the other states UTC-3. - The match ignores case and surrounding whitespace. - Returns `null` when no state matches. ```javascript import { getTimezoneByState } from '@brazilian-utils/brazilian-utils'; getTimezoneByState('SP'); // 'America/Sao_Paulo' getTimezoneByState('am'); // 'America/Manaus' getTimezoneByState('AC'); // 'America/Rio_Branco' getTimezoneByState('PE'); // 'America/Recife' getTimezoneByState('ZZ'); // null ``` Source: [IANA Time Zone Database](https://www.iana.org/time-zones), [Decreto 2.784/1913](https://www.planalto.gov.br/ccivil_03/decreto/historicos/dpl/dpl2784-1913.htm), which set the legal time of Brazil, as amended by [Lei 11.662/2008](https://www.planalto.gov.br/ccivil_03/_ato2007-2010/2008/lei/l11662.htm) and [Lei 12.876/2013](https://www.planalto.gov.br/ccivil_03/_ato2011-2014/2013/lei/l12876.htm). ### getMunicipalities Get the Brazilian municipalities published by the IBGE: every municipality, or only those of one state when `stateCode` is given. - Each municipality (`Municipality`) is `{ code, name, stateCode }`, where `code` is the 7-digit IBGE code. Sorted by name in the "pt-BR" locale. - Only an omitted (or `undefined`) `stateCode` asks for the full list: `null` and `''` return `[]`. - `stateCode` ignores letter case and surrounding whitespace: `'sp'` returns the São Paulo municipalities, as `'SP'` does (up to 2.4.0 it returned `[]`). - Embeds all 5571 municipalities, the same codes as the IBGE [Divisão Territorial Brasileira 2025](https://geoftp.ibge.gov.br/organizacao_do_territorio/estrutura_territorial/divisao_territorial/2025/DTB_2025.zip) (data base 31/12/2025). See [Bundle size](getting-started.md#bundle-size) to lazy-load it via `@brazilian-utils/brazilian-utils/get-municipalities`. ```javascript import { getMunicipalities } from '@brazilian-utils/brazilian-utils'; // Return every Brazilian municipality (sorted by name). getMunicipalities(); // [ // { code: '5200050', name: 'Abadia de Goiás', stateCode: 'GO' }, // { code: '3100104', name: 'Abadia dos Dourados', stateCode: 'MG' }, // { code: '5200100', name: 'Abadiânia', stateCode: 'GO' }, // { code: '3100203', name: 'Abaeté', stateCode: 'MG' }, // { code: '1500107', name: 'Abaetetuba', stateCode: 'PA' }, // ... 5566 more items // ] // Return every municipality of the São Paulo state. getMunicipalities('SP'); // [ // { code: '3500105', name: 'Adamantina', stateCode: 'SP' }, // { code: '3500204', name: 'Adolfo', stateCode: 'SP' }, // { code: '3500303', name: 'Aguaí', stateCode: 'SP' }, // { code: '3500402', name: 'Águas da Prata', stateCode: 'SP' }, // { code: '3500501', name: 'Águas de Lindóia', stateCode: 'SP' }, // ... 640 more items // ] getMunicipalities('ZZ'); // [] ``` Source: [IBGE Localidades](https://servicodados.ibge.gov.br/api/docs/localidades) ### getMunicipalityByCode Look up a Brazilian municipality by its 7-digit IBGE code. - Accepts the code as a string or a non-negative integer, with any non-digit characters of a string stripped. - Returns `{ code, name, stateCode }` (`Municipality`), or `null` when the code is not 7 digits long or matches no municipality. ```javascript import { getMunicipalityByCode } from '@brazilian-utils/brazilian-utils'; getMunicipalityByCode('3550308'); // { code: '3550308', name: 'São Paulo', stateCode: 'SP' } getMunicipalityByCode(3550308); // { code: '3550308', name: 'São Paulo', stateCode: 'SP' } getMunicipalityByCode('0000000'); // null (unknown code) getMunicipalityByCode('123'); // null (not 7 digits) ``` Source: [IBGE Localidades](https://servicodados.ibge.gov.br/api/docs/localidades) ### getCodeByMunicipalityName Look up the 7-digit IBGE code of a Brazilian municipality by its name and the code of its state. It is the offline, synchronous counterpart of `get_code_by_municipality_name` in the Python library, which queries the IBGE API over the network. - The name ignores accents, the cedilla and letter case. Runs of whitespace collapse and the surrounding whitespace is trimmed, but a name written without a space the IBGE name has does not match (`'saopaulo'`). - Takes one object, `{ municipalityName, stateCode }` (`GetCodeByMunicipalityNameParams`), with both fields required. The state code ignores letter case and surrounding whitespace, as every util that takes a state does. It is required, since the same name can belong to municipalities of different states (`'Bom Jesus'` exists in PI, RS and other states). - Returns the code as a string, or `null` when the state code is not a state or no municipality of that state has that name. - Embeds the 5571 municipalities, the same table as `getMunicipalityByCode`. See [Bundle size](getting-started.md#bundle-size) to lazy-load it via `@brazilian-utils/brazilian-utils/get-code-by-municipality-name`. ```javascript import { getCodeByMunicipalityName } from '@brazilian-utils/brazilian-utils'; getCodeByMunicipalityName({ municipalityName: 'Conceição do Coité', stateCode: 'Ba' }); // '2908408' getCodeByMunicipalityName({ municipalityName: 'sao paulo', stateCode: 'sp' }); // '3550308' getCodeByMunicipalityName({ municipalityName: 'Bom Jesus', stateCode: 'RS' }); // '4302303' getCodeByMunicipalityName({ municipalityName: 'São Paulo', stateCode: 'RJ' }); // null (no São Paulo in Rio de Janeiro) getCodeByMunicipalityName({ municipalityName: 'Município Inexistente', stateCode: 'RS' }); // null ``` Source: [IBGE Localidades](https://servicodados.ibge.gov.br/api/docs/localidades) ### getCities Get the names of Brazilian cities: every city, or only those of one state. **Deprecated:** use `getMunicipalities` instead. - Sorted in the "pt-BR" locale. - Any falsy `state` asks for the full list, where `getMunicipalities` returns `[]`. - `state` ignores letter case and surrounding whitespace: `'sp'` returns the São Paulo cities, as `'SP'` does (up to 2.4.0 it returned `[]`). - Embeds all 5571 names (~64.2 KB minified, ~26.4 KB gzipped). See [Bundle size](getting-started.md#bundle-size) to lazy-load it via `@brazilian-utils/brazilian-utils/get-cities`. ```javascript import { getCities } from '@brazilian-utils/brazilian-utils'; // Return all Brazilian cities (sorted alphabetically). getCities(); // [ // 'Abadia de Goiás', // 'Abadia dos Dourados', // 'Abadiânia', // 'Abaeté', // 'Abaetetuba', // 'Abaiara', // 'Abaíra', // 'Abaré', // 'Abatiá', // 'Abdon Batista', // ... 5561 more items // ] // Return all Brazilian cities of the São Paulo state (sorted alphabetically). getCities('SP'); // [ // "Adamantina", // "Adolfo", // "Aguaí", // "Águas da Prata", // "Águas de Lindóia", // "Águas de Santa Bárbara", // "Águas de São Pedro", // "Agudos", // "Alambari", // "Alfredo Marcondes", // ... 635 more items // ] ``` Source: [IBGE Localidades](https://servicodados.ibge.gov.br/api/docs/localidades) ### getMunicipality Get municipality information by IBGE code, or an IBGE code from a municipality name and UF. **Deprecated:** use `getMunicipalityByCode` for a code and `getCodeByMunicipalityName` for a name instead, which are synchronous and offline. - One function handles both directions, based on whether `options` has a `code` or a `municipalityName`/`uf`. The lookup is offline: no network request is made. - The name match ignores accents and case, and every run of whitespace collapses into one space. - Resolves to `null` for an unknown municipality, an unknown UF or invalid input. - `GetMunicipalityOptions`, `GetMunicipalityByCodeOptions` and `GetMunicipalityByNameOptions` are deprecated aliases of the types below. ```javascript import { getMunicipality } from '@brazilian-utils/brazilian-utils'; await getMunicipality({ code: '3550308' }); // ['São Paulo', 'SP'] await getMunicipality({ code: 3550308 }); // ['São Paulo', 'SP'] await getMunicipality({ municipalityName: 'sao paulo', uf: 'sp' }); // '3550308' await getMunicipality({ code: '0000000' }); // null (unknown code) await getMunicipality({ code: '123' }); // null (not 7 digits) ``` ```typescript import { getMunicipality, type GetMunicipalityByCodeParams, type GetMunicipalityByNameParams, type GetMunicipalityParams, } from '@brazilian-utils/brazilian-utils'; const byCode: GetMunicipalityByCodeParams = { code: '3550308' }; const byName: GetMunicipalityByNameParams = { municipalityName: 'sao paulo', uf: 'sp' }; await getMunicipality(byCode); // Promise<[string, string] | null> await getMunicipality(byName); // Promise const lookUp = (options: GetMunicipalityParams) => getMunicipality(options); // (options: GetMunicipalityParams) => Promise<[string, string] | string | null> ``` Source: [IBGE Localidades](https://servicodados.ibge.gov.br/api/docs/localidades) ## Holidays and business days ### getHolidays Get the Brazilian holidays of a year: the national ones and, with a `stateCode`, that state's holidays too. Accepts a year or `{ year, stateCode }` (`GetHolidaysParams`). - Each holiday is a `Holiday` whose `type` (`HolidayType`) is `"national"`, `"state"`, `"optional"` or `"religious"`. Holidays are sorted by date. - "Dia da Consciência Negra", Nov 20, is national from 2024 on. - The first round of the elections, "Eleições (primeiro turno)", is a national holiday in the even years from 1998 on (Código Eleitoral, art. 380): the first Sunday of October, or Nov 15 in 2020 (EC nº 107/2020). The second round is left out, since it is held only where one is needed. Being a Sunday, it never changes a business day count. Before 1998, Lei nº 1.266/1950 made the day of the general elections a national holiday, so the ones held on a weekday are listed too: Oct 3 of 1955 and 1958 ("Eleições gerais") and of 1990 and 1994 ("Eleições (primeiro turno)"). Oct 3, 1960 is left out, since no official text found dates that year's presidential election, and so is the municipal election of Oct 3, 1996. - Each fixed-date national holiday is listed only for the years a federal norm declared it (Sexta-feira Santa, which the federal calendar portarias list as a feriado nacional every year, is listed every year): Nossa Senhora Aparecida from 1980, Natal from 1922, Dia do trabalhador from 1925, Tiradentes up to 1930, from 1933 to 1948 and from 1951, and Finados up to 1948 and from 2003. Lei nº 662/1949 left Finados out of the feriados nacionais that Decreto-lei nº 486/1938 listed, and only Lei nº 10.607/2002 put it back (the Câmara report on its bill: "Só inova ao sugerir o dia de finados"); up to 2.4.0 it was listed every year. The other "festas nacionais" of the first republican calendar (Decreto nº 155-B/1890 and Decreto nº 3/1891: Feb 24, May 3, May 13, Jul 14 and Oct 12) are listed up to 1930, and May 3 (1936 to 1938), Jul 16 and Oct 12 (1936 and 1937) again under Lei nº 108/1935. - The `"optional"` entries are the whole-day pontos facultativos of the federal calendar (Portarias MGI nº 8.617/2023, 9.783/2024 and 11.460/2025, for 2024 to 2026, all of which list both Carnaval days as ponto facultativo, never as feriado nacional): Carnaval Monday and Tuesday and Corpus Christi, the same three days the financial market skips (Resolução CMN nº 4.880/2020), plus the state ones a state norm declares (AM's Dec 8 from 1999, which the state declares for its offices by decree, and PE's Mar 6 in 2008 and 2009). `includeOptional` switches exactly these. The partial ones are left out: Quarta-feira de Cinzas (until 14h), Oct 28 (Dia do Servidor Público) and the Dec 24 and Dec 31 afternoons. - Per-state rules (SC's Sunday shift of a date falling Monday to Saturday, as Decreto SC nº 1.460/2018 did with a Saturday Aug 11; PE's data magna on the first Sunday of March from 2010 to 2017; AL's Nov 30 moved to Monday from a Tuesday and to Friday from a Thursday, DF's, MA's (from 2024) and RJ's (from 2026) Corpus Christi and RJ's Carnaval Tuesday typed `"state"`, dates that stopped being holidays) follow each state's law; see the source for the list. AL's Sep 16 is a state holiday from 2011, as the state's calendar decrees label it before Lei AL nº 9.358/2024. A state law the STF struck down has no entry in any year: RO's Jun 18 (ADI 3940) and AP's Jul 25 (ADI 4820). - Other shifts are not applied and the statutory date is returned: AC's law moves the feriados falling Tuesday to Thursday to the Friday (Lei AC nº 2.126/2009), but the state's own yearly decrees apply it unevenly (2026 moves Jan 20 and leaves Nov 17, a Tuesday, in place). - GO's three dates (Jul 26, Oct 24, Oct 28) are the "feriados estaduais" of the state servants' statute, listed from 1986 (Lei GO nº 9.990/1986, then Lei GO nº 10.460/1988 and Lei GO nº 20.756/2020, art. 269, II); the same statutes made Nov 2 a GO holiday from 1986 to 2002, the years it was not a national one. No Goiás law fixing a data magna as a civil holiday was found. The governor moves Jul 26 by decree every year (2025: Jul 28; 2026: Jul 20), and Oct 28 most years (2025: Oct 27; 2026: Oct 30), so the statutory date returned here is often not the day observed. - Each state holiday is listed only from the first year its state law applied (SP's Jul 9 from 1997, RJ's São Jorge from 2008, SC's Aug 11 from 2004), so an older year has fewer state holidays. - `stateCode` ignores letter case and surrounding whitespace (`'sp'` is `'SP'`). Only an omitted (or `undefined`) `stateCode` asks for the national holidays alone: any other value that is not a state code (`'XX'`, `''`, a value that is not a string) returns `[]`. Up to 2.4.0 an unknown code was ignored and the national holidays were returned, so a typo such as `'sp'` silently dropped the state's holidays. - Returns `[]` when the year is not an integer from 1900 to 2099, or when the argument is neither a number nor an object. ```javascript import { getHolidays } from '@brazilian-utils/brazilian-utils'; // Get the holidays of 2024, national and optional ones getHolidays(2024); // [ // { name: 'Ano novo', date: Date('2024-01-01'), type: 'national' }, // { name: 'Carnaval (segunda-feira)', date: Date('2024-02-12'), type: 'optional' }, // { name: 'Carnaval (terça-feira)', date: Date('2024-02-13'), type: 'optional' }, // { name: 'Sexta-feira Santa', date: Date('2024-03-29'), type: 'national' }, // { name: 'Páscoa', date: Date('2024-03-31'), type: 'religious' }, // { name: 'Tiradentes', date: Date('2024-04-21'), type: 'national' }, // { name: 'Dia do trabalhador', date: Date('2024-05-01'), type: 'national' }, // { name: 'Corpus Christi', date: Date('2024-05-30'), type: 'optional' }, // { name: 'Independência do Brasil', date: Date('2024-09-07'), type: 'national' }, // { name: 'Eleições (primeiro turno)', date: Date('2024-10-06'), type: 'national' }, // { name: 'Nossa Senhora Aparecida', date: Date('2024-10-12'), type: 'national' }, // { name: 'Finados', date: Date('2024-11-02'), type: 'national' }, // { name: 'Proclamação da República', date: Date('2024-11-15'), type: 'national' }, // { name: 'Dia da Consciência Negra', date: Date('2024-11-20'), type: 'national' }, // { name: 'Natal', date: Date('2024-12-25'), type: 'national' }, // ] // Get holidays for a specific state getHolidays({ year: 2024, stateCode: 'SP' }); // Includes national holidays plus state-specific holidays (e.g., "Revolução Constitucionalista") ``` Source: `src/get-holidays/constants.ts`, [Lei nº 662/1949](https://www.planalto.gov.br/ccivil_03/leis/l0662.htm), [Lei nº 9.093/1995](https://www.planalto.gov.br/ccivil_03/leis/l9093.htm). ### isHoliday Check if a date is a Brazilian holiday. Accepts `{ targetDate, stateCode? }` (`IsHolidayParams`). - The check uses `targetDate`'s local calendar date, not its UTC instant. - `stateCode` also considers that state's holidays, read as in `getHolidays` (letter case and surrounding whitespace are ignored). - Returns `false` when `targetDate` is missing or not a valid `Date`, or when `stateCode` is present and is not a state code (`'XX'`, `''`, a value that is not a string), even on a national holiday. - Returns `false` for a year outside 1900 to 2099, where `getHolidays` lists nothing. - The `"optional"` and `"religious"` entries of `getHolidays` count: Carnaval Monday and Tuesday, Corpus Christi and Páscoa make `isHoliday` true. There is no `includeOptional` here, unlike `isBusinessDay`. ```javascript import { isHoliday } from '@brazilian-utils/brazilian-utils'; isHoliday({ targetDate: new Date(2024, 0, 1) }); // true isHoliday({ targetDate: new Date(2024, 6, 9), stateCode: 'SP' }); // true isHoliday(); // false ``` ### isBusinessDay Check if a date is a Brazilian business day (dia útil): not a Saturday, a Sunday or a holiday `getHolidays` lists for its local calendar day. - **Options** (`BusinessDayOptions`, shared by every business day util): `includeOptional` (default `true`) also counts the `"optional"` holidays, Carnaval Monday and Tuesday and Corpus Christi, as non-business days; `includeSaturday` (default `false`) counts Saturday as a business day; `stateCode` also counts that state's holidays. - `includeSaturday` off is a Monday to Friday count. It is not by itself the calendar of banks or courts: the financial market also skips Carnaval Monday and Tuesday and Corpus Christi (Resolução CMN nº 4.880/2020, art. 6º), which the default `includeOptional` covers, and banks close on local holidays; the federal courts also close from Dec 20 to Jan 6, from Holy Wednesday to Easter, on Carnaval Monday and Tuesday, Aug 11, Nov 1 and 2 and Dec 8 (Lei nº 5.010/1966, art. 62), and procedural deadlines follow each court's calendar (CPC art. 216). On, it is the labour law count of the payroll deadline of CLT art. 459 § 1º, the one labour inspection reads through Instrução Normativa MTP nº 2/2021, art. 14, I: "na contagem dos dias será incluído o sábado, excluindo-se o domingo e o feriado, inclusive o municipal". - Sunday and holidays are still excluded with `includeSaturday` on, so a holiday that falls on a Saturday is still not a business day. - The "inclusive o municipal" part of that rule is not covered: `getHolidays` carries national and state holidays only, so a municipal holiday counts here as an ordinary business day. Remove the municipal holidays yourself when a count has to be exact for one municipality. - Returns `false` when `value` is not a valid `Date` or its year is outside 1900 to 2099, or when `stateCode` is present and is not a state code (`'XX'`, `''`, a value that is not a string). Letter case and surrounding whitespace in `stateCode` are ignored. ```javascript import { isBusinessDay } from '@brazilian-utils/brazilian-utils'; isBusinessDay(new Date(2024, 0, 2)); // true (Tuesday, not a holiday) isBusinessDay(new Date(2024, 0, 1)); // false (Ano novo) isBusinessDay(new Date(2024, 0, 6)); // false (Saturday) isBusinessDay(new Date(2024, 0, 6), { includeSaturday: true }); // true (labour law count) isBusinessDay(new Date(2024, 8, 7), { includeSaturday: true }); // false (Independência, a holiday on a Saturday) isBusinessDay(new Date(2024, 0, 7), { includeSaturday: true }); // false (Sunday is never included) isBusinessDay(new Date(2024, 1, 12)); // false (Carnaval Monday, optional holiday, counts by default) isBusinessDay(new Date(2024, 1, 13)); // false (Carnaval Tuesday, optional holiday, counts by default) isBusinessDay(new Date(2024, 1, 13), { includeOptional: false }); // true isBusinessDay(new Date(2024, 6, 9), { stateCode: 'SP' }); // false (Revolução Constitucionalista) isBusinessDay(new Date(2024, 6, 9)); // true (state holiday ignored without stateCode) isBusinessDay(new Date('not a date')); // false ``` ### addBusinessDays Add a number of Brazilian business days (dias úteis) to a date, skipping Saturdays, Sundays and the holidays `isBusinessDay` skips. Signature: `addBusinessDays(date, amount, options?)`, the same as date-fns. - **Options** (`BusinessDayOptions`, shared with `isBusinessDay`): `includeOptional` (default `true`) also skips Carnaval Monday and Tuesday and Corpus Christi; `includeSaturday` (default `false`) counts Saturday as a business day; `stateCode` also skips that state's holidays. - Returns a new `Date`, time of day preserved; `date` is never mutated. - An `amount` of `0` returns the same date, even on a weekend or holiday. A negative `amount` walks backwards. - Returns `null` when `date` is invalid, `amount` is not a finite integer, `stateCode` is present and is not a state code, or the result leaves the years 1900 to 2099. ```javascript import { addBusinessDays } from '@brazilian-utils/brazilian-utils'; addBusinessDays(new Date(2024, 0, 2, 12), 1); // Date, 2024-01-03 12:00 (next day is already a business day) addBusinessDays(new Date(2024, 11, 31, 12), 1); // Date, 2025-01-02 12:00 (2025-01-01 is Ano novo, skipped) addBusinessDays(new Date(2024, 0, 5, 12), -1); // Date, 2024-01-04 12:00 (walks backwards) addBusinessDays(new Date(2024, 0, 6, 12), 0); // Date, 2024-01-06 12:00 (unchanged, even though Saturday is not a business day) addBusinessDays(new Date(2024, 0, 5, 12), 1, { includeSaturday: true }); // Date, 2024-01-06 12:00 (labour law count, Saturday counts) addBusinessDays(new Date(2024, 10, 1, 12), 1, { includeSaturday: true }); // Date, 2024-11-04 12:00 (2024-11-02 is Finados, a holiday on a Saturday) addBusinessDays(new Date(2024, 6, 8, 12), 1, { stateCode: 'SP' }); // Date, 2024-07-10 12:00 (2024-07-09 is Revolução Constitucionalista in SP, skipped) addBusinessDays(new Date('not a date'), 1); // null addBusinessDays(new Date(2024, 0, 2), 1.5); // null (not an integer) ``` ### subBusinessDays Subtract a number of Brazilian business days (dias úteis) from a date. `subBusinessDays(date, amount, options?)` is `addBusinessDays(date, -amount, options)`. - Same rules as `addBusinessDays`, `BusinessDayOptions` included. A negative `amount` walks forwards. ```javascript import { subBusinessDays } from '@brazilian-utils/brazilian-utils'; subBusinessDays(new Date(2024, 0, 5, 12), 1); // Date, 2024-01-04 12:00 (previous day is already a business day) subBusinessDays(new Date(2024, 0, 8, 12), 1); // Date, 2024-01-05 12:00 (walks back over the weekend) subBusinessDays(new Date(2025, 0, 2, 12), 1); // Date, 2024-12-31 12:00 (2025-01-01 is Ano novo, skipped) subBusinessDays(new Date(2024, 0, 5, 12), -1); // Date, 2024-01-08 12:00 (walks forwards) subBusinessDays(new Date(2024, 0, 6, 12), 0); // Date, 2024-01-06 12:00 (unchanged, even though Saturday is not a business day) subBusinessDays(new Date(2024, 0, 8, 12), 1, { includeSaturday: true }); // Date, 2024-01-06 12:00 (labour law count, Saturday counts) subBusinessDays(new Date(2024, 10, 4, 12), 1, { includeSaturday: true }); // Date, 2024-11-01 12:00 (2024-11-02 is Finados, a holiday on a Saturday) subBusinessDays(new Date(2024, 6, 10, 12), 1, { stateCode: 'SP' }); // Date, 2024-07-08 12:00 (2024-07-09 is Revolução Constitucionalista in SP, skipped) subBusinessDays(new Date('not a date'), 1); // null subBusinessDays(new Date(2024, 0, 2), 1.5); // null (not an integer) ``` To get the n-th business day of a month, or the last one, start from the day just outside the month: ```javascript import { addBusinessDays, subBusinessDays } from '@brazilian-utils/brazilian-utils'; // n-th business day of the month: add n from the last day of the month before addBusinessDays(new Date(2024, 0, 0), 5); // Date, 2024-01-08 00:00 (5th business day of January 2024) addBusinessDays(new Date(2024, 1, 0), 10); // Date, 2024-02-16 00:00 (10th of February 2024, Carnaval Monday and Tuesday skipped) // last business day of the month: subtract 1 from the first day of the month after subBusinessDays(new Date(2024, 3, 1), 1); // Date, 2024-03-28 00:00 (2024-03-29 is Sexta-feira Santa, then a weekend) subBusinessDays(new Date(2024, 1, 1), 2); // Date, 2024-01-30 00:00 (2nd to last of January 2024) // payroll deadline of CLT art. 459 § 1º: the 5th business day in the labour law count addBusinessDays(new Date(2024, 2, 0), 5, { includeSaturday: true }); // Date, 2024-03-06 00:00 (2024-03-02, a Saturday, counts; the Monday to Friday count gives 2024-03-07) addBusinessDays(new Date(2024, 10, 0), 5, { includeSaturday: true }); // Date, 2024-11-07 00:00 (2024-11-02 is Finados, a holiday on a Saturday) subBusinessDays(new Date(2024, 8, 1), 1, { includeSaturday: true }); // Date, 2024-08-31 00:00 (last business day of August 2024, a Saturday) ``` - An `n` beyond the business days of the month lands in the next month (`addBusinessDays(new Date(2024, 0, 0), 23)` is 2024-02-01, January 2024 has 22); compare `getMonth()` when that matters. - The payroll "quinto dia útil" of CLT art. 459 § 1º is the labour law count: pass `{ includeSaturday: true }`. Municipal holidays, which that count also excludes, are not known to the library, so a municipal holiday early in the month still has to be accounted for by the caller. - The n-th business day of January 1900 and the last business day of December 2099 return `null`, since the recipe starts from a day outside the supported years (31 December 1899 and 1 January 2100). ### differenceInBusinessDays Count the Brazilian business days (dias úteis) between two dates. Signature: `differenceInBusinessDays(laterDate, earlierDate, options?)`, the same as date-fns. - **Options** (`BusinessDayOptions`, shared with `isBusinessDay`): `includeOptional` (default `true`) also skips Carnaval Monday and Tuesday and Corpus Christi; `includeSaturday` (default `false`) counts Saturday as a business day; `stateCode` also skips that state's holidays. - Counts `earlierDate` when it is a business day and every business day strictly between the two dates; `laterDate` is never counted. The time of day is ignored. - The result is negative when `laterDate` is before `earlierDate`, and `0` on the same calendar day. - Returns `null` when either date is not a valid `Date` or is outside the years 1900 to 2099, or `stateCode` is present and is not a state code. ```javascript import { differenceInBusinessDays } from '@brazilian-utils/brazilian-utils'; differenceInBusinessDays(new Date(2024, 0, 2), new Date(2024, 0, 1)); // 0 (Jan 1 is Ano novo, not counted) differenceInBusinessDays(new Date(2024, 0, 3), new Date(2024, 0, 2)); // 1 (Jan 2 counted, a Tuesday; Jan 3 is not) differenceInBusinessDays(new Date(2024, 0, 2), new Date(2024, 0, 3)); // -1 (the later date comes first, so the count is negative) differenceInBusinessDays(new Date(2024, 0, 2), new Date(2024, 0, 2)); // 0 (same day) differenceInBusinessDays(new Date(2024, 0, 8), new Date(2024, 0, 1)); // 4 (Monday to Friday count, 2024-01-02 to 2024-01-05) differenceInBusinessDays(new Date(2024, 0, 8), new Date(2024, 0, 1), { includeSaturday: true }); // 5 (2024-01-06, a Saturday, also counts) differenceInBusinessDays(new Date(2024, 10, 4), new Date(2024, 10, 1), { includeSaturday: true }); // 1 (2024-11-02 is Finados, a holiday on a Saturday) differenceInBusinessDays(new Date(2024, 6, 10), new Date(2024, 6, 8), { stateCode: 'SP' }); // 1 (2024-07-09 is a state holiday in SP) differenceInBusinessDays(new Date(), new Date('not a date')); // null ``` ## Passport ### isValidPassport Check if a Brazilian passport number is valid: 2 letters followed by 6 digits. - There is no check digit, so a well-formed number is not necessarily a real passport. - The 2 letters (the "série") and 6 digits come from the Polícia Federal's FAQ; no norm defines the number (neither the Decreto nº 5.978/2006 nor the IN nº 173-DG/PF/2020, as amended up to the IN nº 283/2024), and the FAQ lists no forbidden letter. ```javascript import { isValidPassport } from '@brazilian-utils/brazilian-utils'; isValidPassport('AB123456'); // true isValidPassport('ab123456'); // true (case-insensitive) isValidPassport('AB-123.456'); // true (symbols are ignored) isValidPassport('12345678'); // false ``` Source: [Polícia Federal FAQ](https://www.gov.br/pf/pt-br/assuntos/passaporte/ajuda/duvidas_/caderneta/caderneta-numero-onde-fica-e). ### formatPassport Format a Brazilian passport number: uppercase, without symbols, capped to 8 characters. It is the same operation as `parsePassport`, of which it is an alias. ```javascript import { formatPassport } from '@brazilian-utils/brazilian-utils'; formatPassport('ab123456'); // 'AB123456' formatPassport('AB-123.456'); // 'AB123456' ``` ### parsePassport Remove all non-alphanumeric characters from a passport number, uppercase the result, and cap it to 8 characters. ```javascript import { parsePassport } from '@brazilian-utils/brazilian-utils'; parsePassport('AB-123.456'); // 'AB123456' parsePassport(' AB 123 456 '); // 'AB123456' ``` ### generatePassport Generate a random valid Brazilian passport number. ```javascript import { generatePassport } from '@brazilian-utils/brazilian-utils'; generatePassport(); // 'RY393097' ``` ## CNH ### isValidCnh Check if a CNH is valid. Spaces, dots, hyphens and slashes are ignored; any other character makes the value invalid. - A value whose 11 digits are all the same is rejected, so `'11111111111'` is invalid. - The first check digit keeps a remainder of 1 as `1`, as real registry numbers do. Resolução CONTRAN nº 886/2021, art. 4º § 1º, whose remainder of 0 or 1 gives `0`, speaks of "O dígito verificador" without naming the number: written in the singular right after the Número do Espelho da CNH (the only number of the article with a single check digit), it reads best as that digit's rule, but it is worded generically and gives no weights, so it is no source for the 2 check digits of the registry number; no official text publishes their weights. Resoluções CONTRAN nº 976/2022, nº 998/2023 and nº 1.006/2024 amend Resolução nº 886/2021, none of them in art. 4º. Resolução CONTRAN nº 1.020/2025, the newer habilitação norm, repeats the layout in its art. 10 ("nove caracteres e dois dígitos verificadores") with no check digit rule and does not revoke the 886 (art. 140). ```javascript import { isValidCnh } from '@brazilian-utils/brazilian-utils'; isValidCnh('00000000119'); // true isValidCnh('000000001-19'); // true (hyphen before the check digits) isValidCnh('ab00000000119'); // false (letters are rejected) ``` Source: [Resolução CONTRAN nº 886/2021, art. 4º](https://www.gov.br/transportes/pt-br/assuntos/transito/conteudo-contran/resolucoes/Resolucao8862021F.pdf), [Resolução CONTRAN nº 1.020/2025, art. 10](https://www.gov.br/transportes/pt-br/assuntos/transito/conteudo-contran/resolucoes/Resolucao10202025.pdf); weights per [siga0984](https://siga0984.wordpress.com/2019/05/01/algoritmos-validacao-de-cnh/). ### formatCnh Format a CNH. - **Options** (`FormatCnhOptions`): `pad` left-pads the value with zeros to the full 11 digits before masking (default `false`); `obfuscate` hides the first 3 digits and the 2 check digits. An empty value, or one without digits, gives `''` even with `pad`. - `obfuscate` is applied after `pad`. - No authority publishes a masking rule for the CNH, so `obfuscate` applies the one the Leis de Diretrizes Orçamentárias set for publishing a CPF ("ocultar os três primeiros dígitos e os dois dígitos verificadores", Lei nº 14.194/2021, art. 149, first set by Lei nº 12.309/2010, art. 87, § 5º), a number with the same structure. ```javascript import { formatCnh } from '@brazilian-utils/brazilian-utils'; formatCnh('02650306461'); // 026503064-61 formatCnh('2650306461', { pad: true }); // 026503064-61 formatCnh('02650306461', { obfuscate: true }); // ***503064-** ``` ### parseCnh Remove CNH formatting, keep only digits, and cap the result to 11 digits. ```javascript import { parseCnh } from '@brazilian-utils/brazilian-utils'; parseCnh('026503064-61'); // '02650306461' ``` ### generateCnh Generate a valid random CNH. ```javascript import { generateCnh } from '@brazilian-utils/brazilian-utils'; generateCnh(); // '02650306461' ``` Source: [Lei nº 14.194/2021, art. 149](https://www.planalto.gov.br/ccivil_03/_ato2019-2022/2021/lei/L14194.htm), the CPF masking rule `obfuscate` borrows, first set by [Lei nº 12.309/2010, art. 87, § 5º](https://www.planalto.gov.br/ccivil_03/_ato2007-2010/2010/lei/l12309.htm) and repeated by the later LDOs ([Lei nº 15.321/2025, art. 163](https://www.planalto.gov.br/ccivil_03/_ato2023-2026/2025/lei/L15321.htm#art163), the one for 2026, repeats it). ## Legal nature ### isValidLegalNature Check if a legal nature code exists in the official list, the IBGE/CONCLA "Natureza Jurídica 2021" table. Accepts a string with the 4 digits or with the `NNN-N` mask, or a non-negative safe integer. - A separator run (space, `.`, `-` or `/`) is only read between the third and the fourth digit, so `'2-0-6-2'` is rejected. - The 92 codes in force are accepted, plus the 8 a past revision retired. `getLegalNature` tells them apart (`legacy: true`). ```javascript import { isValidLegalNature } from '@brazilian-utils/brazilian-utils'; isValidLegalNature('2062'); // true isValidLegalNature(2062); // true isValidLegalNature('206-2'); // true isValidLegalNature('2208'); // true (retired by a past revision, still accepted) isValidLegalNature('9999'); // false isValidLegalNature('2-0-6-2'); // false (a separator only fits after the third digit) ``` Source: [CONCLA, Natureza Jurídica 2021](https://concla.ibge.gov.br/estrutura/natjur-estrutura/natureza-juridica-2021) and its [detailed structure PDF](https://concla.ibge.gov.br/images/concla/documentacao/CONCLA-TNJ2021-EstruturaDetalhada.pdf). ### formatLegalNature Format a legal nature code. Use `isValidLegalNature` to check a code. - **Options** (`FormatLegalNatureOptions`): `pad` first left-pads the value with zeros to the 4 digits of a complete code (default `false`). An empty value, or one without digits, gives `''` even with `pad`. ```javascript import { formatLegalNature } from '@brazilian-utils/brazilian-utils'; formatLegalNature('2062'); // 206-2 formatLegalNature(2062); // 206-2 formatLegalNature('206'); // 206 (masked as far as it goes) formatLegalNature('62', { pad: true }); // 006-2 (padded to 4 digits first) ``` ### parseLegalNature Remove legal nature formatting, keep only digits, and cap the result to 4 digits. ```javascript import { parseLegalNature } from '@brazilian-utils/brazilian-utils'; parseLegalNature('206-2'); // '2062' ``` ### generateLegalNature Generate a random valid legal nature code. Only the 92 codes in force are drawn, never a retired one. ```javascript import { generateLegalNature } from '@brazilian-utils/brazilian-utils'; generateLegalNature(); // '2062' ``` ### getLegalNature Look a legal nature code up in the official IBGE/CONCLA table. Returns `null` for an unknown code. - The entry (`LegalNature`) also carries the CONCLA category of the code, given by its first digit. - A code a past revision retired comes back with `legacy: true` and the `currentCode` it corresponds to today, or `currentCode: null` when there is no successor (`2100`, `3050` and `3123`). Codes in force have `legacy: false` and no `currentCode`. | Retired code | Description | Corresponds to | | --- | --- | --- | | `2076` | Sociedade Empresária em Nome Coletivo | `2070`, the code the 2003.1 revision renumbered it to, same denomination | | `2100` | Sociedade Mercantil de Capital e Indústria | none, marked "categoria extinta" by the 2003.1 x 2009 correspondence | | `2208` | Entidade Binacional Itaipu | `2275` Empresa Binacional | | `3042` | Organização Social | `3069` Fundação Privada; the 2014 revision later created `3301` Organização Social (OS), where an entity qualified as one is classified today | | `3050` | Organização da Sociedade Civil de Interesse Público (Oscip) | none, an Oscip is classified by the form it takes (`3999` or `3069`) | | `3093` | Unidade Executora (Programa Dinheiro Direto na Escola) | `3999` Associação Privada | | `3123` | Partido Político | none, the 2014 revision split it into `3255`, `3263` and `3271` | | `5002` | Organização Internacional e Outras Instituições Extraterritoriais | `5010` Organização Internacional, the code it was opened into alongside `5029` and `5037` | ```javascript import { getLegalNature } from '@brazilian-utils/brazilian-utils'; getLegalNature('2062'); // { // code: '2062', // description: 'Sociedade Empresária Limitada', // category: { code: '2', description: 'Entidades Empresariais' }, // legacy: false, // } getLegalNature('2208'); // { // code: '2208', // description: 'Entidade Binacional Itaipu', // category: { code: '2', description: 'Entidades Empresariais' }, // legacy: true, // currentCode: '2275', // } getLegalNature('3123')?.currentCode; // null (retired without a successor) getLegalNature('206-2')?.code; // '2062' getLegalNature('206.2')?.category.description; // 'Entidades Empresariais' getLegalNature(206.2); // null (a number is only read when it is a non-negative safe integer: write the dotted form as a string) getLegalNature('0000'); // null ``` Source: [CONCLA, Natureza Jurídica 2021](https://concla.ibge.gov.br/estrutura/natjur-estrutura/natureza-juridica-2021). ### getLegalNatures Get the legal nature map keyed by code. Only the 92 codes in force are listed by default. - **Options** (`GetLegalNaturesParams`): `includeLegacy` (default `false`) adds the 8 retired codes. ```javascript import { getLegalNatures } from '@brazilian-utils/brazilian-utils'; const legalNatures = getLegalNatures(); legalNatures['2062']; // 'Sociedade Empresária Limitada' Object.keys(legalNatures).length; // 92 legalNatures['2208']; // undefined (retired by a past revision) getLegalNatures({ includeLegacy: true })['2208']; // 'Entidade Binacional Itaipu' ``` ### getLegalNaturesByCategory Get every legal nature of a CONCLA category, the group given by the first digit of the code. The category is accepted as a string or as a number. - Categories: `1` Administração Pública, `2` Entidades Empresariais, `3` Entidades sem Fins Lucrativos, `4` Pessoas Físicas and `5` Organizações Internacionais e Outras Instituições Extraterritoriais. - **Options** (`GetLegalNaturesByCategoryOptions`): `includeLegacy` (default `false`) adds the retired codes of the category. - The entries come back sorted by code. An unknown category returns `[]`. ```javascript import { getLegalNaturesByCategory } from '@brazilian-utils/brazilian-utils'; getLegalNaturesByCategory('4')[0]; // { // code: '4014', // description: 'Empresa Individual Imobiliária', // category: { code: '4', description: 'Pessoas Físicas' }, // legacy: false, // } getLegalNaturesByCategory(4).length; // 6 getLegalNaturesByCategory('2').length; // 30 getLegalNaturesByCategory('2', { includeLegacy: true }).length; // 33 getLegalNaturesByCategory('9'); // [] ``` ## Voter ID (título de eleitor) ### isValidVoterId Check if a voter ID number is valid. A voter ID has at most 12 digits, so a 13-digit value is rejected. - A voter ID is an 8-digit sequential number, a 2-digit federative union code (`01` to `28`) and 2 check digits. - The TSE drops the leading zeros of the sequential number when it issues the ID, so a shorter value is read as the ID without them and left padded with zeros to 12 digits before it is checked (`123450159` is checked as `000123450159`). At least one sequential digit is required: the shortest accepted value has 5 digits. - Whitespace, dots, hyphens and slashes are accepted around and between the groups. Any other character makes the value invalid. - Resolução TSE nº 23.659/2021, art. 36, which revoked Resolução TSE nº 21.538/2003 (art. 140), fixes the layout, the federative union table and two check digits "determinados com base no 'Módulo 11'". It gives no weights and no rule per state: the weights, and the rule that turns a remainder of 0 into 1 for São Paulo (`01`) and Minas Gerais (`02`), have no official source and follow the community references below. ```javascript import { generateVoterId, isValidVoterId } from '@brazilian-utils/brazilian-utils'; const voterId = generateVoterId('SP'); isValidVoterId(voterId); // true isValidVoterId('102385010671'); // true (12 digits) isValidVoterId('123450159'); // true (000123450159 issued without its leading zeros) isValidVoterId('1234567880191'); // false (13 digits, more than the 12 the TSE allows) isValidVoterId('123456780124'); // false (invalid check digits) ``` Source: [Resolução TSE nº 23.659/2021, art. 36](https://www.tse.jus.br/legislacao/compilada/res/2021/resolucao-no-23-659-de-26-de-outubro-de-2021) ("composto por até 12 algarismos", "os oito primeiros algarismos serão sequenciados, desprezando-se, na emissão, os zeros à esquerda"), [brutils](https://github.com/brazilian-utils/python/blob/main/brutils/voter_id.py) and [siga0984](https://siga0984.wordpress.com/2019/05/01/algoritmos-validacao-de-titulo-de-eleitor/). ### formatVoterId Format a voter ID number with the 12-digit grouping `0000 0000 00 00`. - **Options** (`FormatVoterIdOptions`): `pad` left pads the value with zeros up to 12 digits, restoring the leading zeros of a voter ID issued without them; `obfuscate` hides the first 3 digits and the 2 check digits, leaving the federative union code visible. The mask hides by position, so pass `pad` with `obfuscate` for a voter ID given as a number, which has lost its leading zeros: without it the mask shifts onto the check digits. An empty value, or one without digits, gives `''` even with `pad`. - Without `pad`, a shorter value is formatted from the left, as a partially typed ID. - Digits past the 12th are dropped. - No authority publishes a masking rule for the voter ID, so `obfuscate` applies the one the Leis de Diretrizes Orçamentárias set for publishing a CPF ("ocultar os três primeiros dígitos e os dois dígitos verificadores", Lei nº 14.194/2021, art. 149, first set by Lei nº 12.309/2010, art. 87, § 5º), a number with the same structure. ```javascript import { formatVoterId } from '@brazilian-utils/brazilian-utils'; formatVoterId('123456780175'); // '1234 5678 01 75' formatVoterId('123456780175', { obfuscate: true }); // '***4 5678 01 **' formatVoterId('123450159', { pad: true }); // '0001 2345 01 59' formatVoterId('123450159'); // '1234 5015 9' (read as a partially typed ID) ``` ### parseVoterId Remove voter ID formatting, keep only digits, and cap the result to 12 digits. A shorter value is kept as it is, without adding leading zeros. ```javascript import { parseVoterId } from '@brazilian-utils/brazilian-utils'; parseVoterId('1234 5678 01 75'); // '123456780175' parseVoterId('12345 01 59'); // '123450159' ``` ### generateVoterId Generate a valid random voter ID number. The optional `state` argument (`StateCode`, or `"ZZ"` for a voter ID issued abroad) sets the federative union code. - `state` ignores letter case and surrounding whitespace (`'sp'` is `'SP'`). An unknown state, or a value that is not a string, falls back to `"ZZ"` (UF `28`). - The result always has 12 digits, the leading zeros of the sequential number included; the same ID without them is valid too. ```javascript import { generateVoterId } from '@brazilian-utils/brazilian-utils'; generateVoterId(); // valid random voter ID (abroad, "ZZ") generateVoterId('SP'); // valid random voter ID for Sao Paulo generateVoterId('XX'); // falls back to "ZZ" instead of throwing ``` Source: [Lei nº 14.194/2021, art. 149](https://www.planalto.gov.br/ccivil_03/_ato2019-2022/2021/lei/L14194.htm), the CPF masking rule `obfuscate` borrows, first set by [Lei nº 12.309/2010, art. 87, § 5º](https://www.planalto.gov.br/ccivil_03/_ato2007-2010/2010/lei/l12309.htm) and repeated by the later LDOs ([Lei nº 15.321/2025, art. 163](https://www.planalto.gov.br/ccivil_03/_ato2023-2026/2025/lei/L15321.htm#art163), the one for 2026, repeats it). ### getVoterIdInfo Read the fields of a voter ID, as a `VoterIdInfo`, or `null` when `isValidVoterId` would return `false`. - Fields: `sequentialNumber` (8 digits), `federativeUnion` (the code `'01'` to `'28'`), `stateCode` (a `StateCode`, or `null` for `'28'`, the voters abroad) and `checkDigits` (2 digits). Codes are strings that keep their leading zeros. - A voter ID issued without the leading zeros of its sequential number is read as `isValidVoterId` reads it, left padded with zeros to 12 digits: `'123450159'` gives the `sequentialNumber` `'00012345'`. - The `stateCode` is the federative union of the registration, not necessarily where the voter lives today. ```javascript import { getVoterIdInfo } from '@brazilian-utils/brazilian-utils'; getVoterIdInfo('1023 8501 06 71'); // { // sequentialNumber: '10238501', // federativeUnion: '06', // stateCode: 'PR', // checkDigits: '71', // } getVoterIdInfo('000000002801'); // { sequentialNumber: '00000000', federativeUnion: '28', stateCode: null, checkDigits: '01' } getVoterIdInfo('123456780124'); // null (invalid check digits) ``` Source: [Resolução TSE nº 23.659/2021, art. 36](https://www.tse.jus.br/legislacao/compilada/res/2021/resolucao-no-23-659-de-26-de-outubro-de-2021). ## CNS ### isValidCns Check if a CNS (Cartão Nacional de Saúde) number is valid, the SUS (Sistema Único de Saúde) identifier of a user, health professional or health facility. The value must be the 15 digits, optionally split into the printed groups of 3-4-4-4 by whitespace, `.`, `-` or `/`. - Definitive cards start with 1 or 2, provisional ones with 7, 8 or 9; each has its own modulus 11 rule. - A number starting with 5 is rejected. The DATASUS validation routines ([Wayback Machine copy](https://web.archive.org/web/20190106003442/http://cartaonet.datasus.gov.br/Rotina_JavaScript.doc) of the file the cartaonet.datasus.gov.br site published) cover only the numbers that start with 1 or 2 (definitive) and with 7, 8 or 9 (provisional), as ANVISA does; no official document names the prefix 5, which the e-SUS APS page accepts. ```javascript import { isValidCns } from '@brazilian-utils/brazilian-utils'; isValidCns('123456789010000'); // true (definitive) isValidCns('100000000060018'); // true (definitive, raw check digit 10, suffix 001) isValidCns('700000000000005'); // true (provisional) isValidCns('123.4567-8901/0000'); // true (any of the mask characters) isValidCns(-123456789010000); // false (not a non-negative safe integer) isValidCns('123456789010001'); // false (wrong check digit) isValidCns('12345678901'); // false (wrong length) isValidCns('abc123456789010000'); // false (not written as a CNS) ``` Source: [DATASUS validation routines](https://web.archive.org/web/20190106003442/http://cartaonet.datasus.gov.br/Rotina_JavaScript.doc) (Wayback Machine copy), [ANVISA CNS validation page](https://rni-docs.anvisa.gov.br/docs/regras_gerais/validacoes/validacaoCNS/) and the [e-SUS APS page](https://integracao.esusab.ufsc.br/ledi/documentacao/regras/algoritmo_CNS.html). ### formatCns Format a CNS (Cartão Nacional de Saúde) number into the common display groups of 3-4-4-4 digits separated by spaces. - **Options** (`FormatCnsOptions`): `pad` left-pads the value with zeros up to the 15 slots of the pattern before masking (default `false`). An empty value, or one without digits, gives `''` even with `pad`. ```javascript import { formatCns } from '@brazilian-utils/brazilian-utils'; formatCns('123456789010000'); // '123 4567 8901 0000' formatCns(123456789010000); // '123 4567 8901 0000' formatCns('89010001', { pad: true }); // '000 0000 8901 0001' ``` ### parseCns Remove CNS (Cartão Nacional de Saúde) formatting, keep only digits, and cap the result to 15 digits. ```javascript import { parseCns } from '@brazilian-utils/brazilian-utils'; parseCns('123 4567 8901 0000'); // '123456789010000' ``` ## Certidão (civil registry certificate) ### isValidCertidao Check if the matrícula of a certidão de registro civil (birth, marriage, death and the other acts of a registro civil das pessoas naturais) is valid. Only a string is accepted: the 32 digits of a matrícula are more than a JavaScript number can hold. The matrícula has 32 digits, printed as `000000 00 00 0000 0 00000 000 0000000 00`: | Digits | Field | | --- | --- | | 6 | CNS da serventia | | 2 | acervo | | 2 | serviço, always `55` | | 4 | ano | | 1 | tipo do livro | | 5 | livro | | 3 | folha | | 7 | termo | | 2 | dígitos verificadores | - **Options** (`IsValidCertidaoOptions`): `accept` narrows the valid book types (`CertidaoType`) to the listed ones (default: every type). - The serviço must be `55`, and the book-type digit one of the codes 1 to 9: 1 to 7 are the books of art. 473, V (Provimento CNJ nº 149/2023, redação of the Provimento CN nº 182/2024); 8 (`"emancipation"`, Livro E desdobrado for emancipações) and 9 (`"interdiction"`, Livro E desdobrado for interdições) come from the Provimento CNJ nº 3/2009, art. 7º, revoked by the Provimento CNJ nº 63/2017, and are kept so the certidões issued under it from 2010 on still validate. `0` is rejected. - Accepts the value masked or not, with whitespace between and around the groups. - No official document publishes the check digit algorithm: art. 473, IX only names the two digits, the revoked Provimento CNJ nº 3/2009 had them computed by a program the CNJ handed to the registrars, and the Caixa's Cadastro NIS layout says only "módulo 11". The weights and the remainder rule follow the community references below. ```javascript import { isValidCertidao } from '@brazilian-utils/brazilian-utils'; isValidCertidao('104539 01 55 2013 1 00012 021 0000123 21'); // true isValidCertidao('09430001552010100020112000012087'); // true isValidCertidao('104539 01 55 2013 1 00012 021 0000123 22'); // false (invalid check digits) isValidCertidao('09400301542011100110002005191744'); // false (serviço is not 55) isValidCertidao('10453901552013900012021000012398'); // true (book code 9, Provimento CNJ nº 3/2009) isValidCertidao('10453901552013000012021000012387'); // false (book code 0 names no book) isValidCertidao('123456'); // false (wrong length) isValidCertidao('104539 01 55 2013 1 00012 021 0000123 21', { accept: ['birth'] }); // true isValidCertidao('104539 01 55 2013 1 00012 021 0000123 21', { accept: ['death'] }); // false ``` Source: [art. 473 of the Código Nacional de Normas da Corregedoria Nacional de Justiça](https://atos.cnj.jus.br/atos/detalhar/5243); check digits per [ghiorzi.org](http://ghiorzi.org/DVnew.htm) and [validation-br](https://github.com/klawdyo/validation-br/blob/feat-certidao/src/certidao.ts). ### formatCertidao Format the matrícula of a certidão de registro civil into the printed mask of art. 473. The 32 digits are grouped as 6 2 2 4 1 5 3 7 2 and separated by spaces. - **Options** (`FormatCertidaoOptions`): `pad` left-pads the value with zeros up to 32 digits (default `false`). An empty value, or one without digits, gives `''` even with `pad`. - A number is accepted when it is a non-negative safe integer, so a full 32-digit matrícula has to be a string. Any other number returns `''`. ```javascript import { formatCertidao } from '@brazilian-utils/brazilian-utils'; formatCertidao('10453901552013100012021000012321'); // '104539 01 55 2013 1 00012 021 0000123 21' formatCertidao('104539.01.55.2013.1.00012.021.0000123-21'); // '104539 01 55 2013 1 00012 021 0000123 21' formatCertidao('1552010100020112000012087', { pad: true }); // '000000 01 55 2010 1 00020 112 0000120 87' formatCertidao(104539015520); // '104539 01 55 20' (a number is read as the string of its digits) formatCertidao(1045390155.2); // '' (not a non-negative safe integer) ``` Source: [art. 473 of the Código Nacional de Normas](https://atos.cnj.jus.br/atos/detalhar/5243). ### parseCertidao Remove the formatting of the matrícula of a certidão de registro civil, keep only digits, and cap the result to 32 digits. ```javascript import { parseCertidao } from '@brazilian-utils/brazilian-utils'; parseCertidao('104539 01 55 2013 1 00012 021 0000123 21'); // '10453901552013100012021000012321' ``` ### getCertidaoInfo Parse the matrícula of a certidão de registro civil into its fields. Accepts the same input forms as `isValidCertidao` and returns `null` when the matrícula is not valid. - Returns `null` also for a serviço other than `55` and for the book code `0`. - Art. 473, V lists the book codes 1 to 7, from "1: Livro A (Nascimento)" to "7: Livro E (Demais atos relativos ao registro civil)". The codes 8 (emancipação) and 9 (interdição) of the Provimento CNJ nº 3/2009, art. 7º, revoked by the Provimento CNJ nº 63/2017, are not in it but are still read, as `"emancipation"` and `"interdiction"`, since the certidões issued under it from 2010 on carry them and remain valid documents. The `CertidaoInfo` result carries: | Key | Description | | --- | --- | | `registryCns` | The 6 digit CNS (Código Nacional de Serventia) of the serventia that issued the act. | | `acervo` | Acervo the book belongs to: `"01"` the serventia's own, `"02"` and up one per acervo it absorbed. Art. 473, §§ 3º to 5º splits the absorbed ones by the date the origin serventia was extinguished or deactivated. Up to 31/12/2009: the CNS of the incorporating unit and an acervo code from `"02"` up, one per incorporation. From 01/01/2010 on: the CNS of the incorporated unit itself and the code `"01"`, counted as that unit's own acervo. An acervo split between two or more successor serventias gets each successor's own CNS with the code `"02"`. | | `service` | Service rendered by the serventia, always `"55"`, the registro civil das pessoas naturais. | | `year` | Four digit year the act was recorded. | | `type` | The book the act belongs to: `"birth"`, `"marriage"`, `"religious-marriage"`, `"death"`, `"stillbirth"`, `"banns"`, `"other"`, or, for the codes 8 and 9 of the Provimento CNJ nº 3/2009, `"emancipation"` and `"interdiction"`. | | `typeCode` | Raw book code, 1 to 9, as printed in the fifteenth position of the matrícula. | | `book` | The 5 digit book (livro) number, zero padded. | | `page` | The 3 digit page (folha) number, zero padded. | | `term` | The 7 digit term (termo) number, zero padded. | | `checkDigits` | The 2 modulus 11 check digits of the matrícula. | ```javascript import { getCertidaoInfo } from '@brazilian-utils/brazilian-utils'; getCertidaoInfo('104539 01 55 2013 1 00012 021 0000123 21'); // { // registryCns: '104539', // acervo: '01', // service: '55', // year: 2013, // type: 'birth', // typeCode: 1, // book: '00012', // page: '021', // term: '0000123', // checkDigits: '21' // } getCertidaoInfo('invalid'); // null ``` Source: [art. 473 of the Código Nacional de Normas da Corregedoria Nacional de Justiça](https://atos.cnj.jus.br/atos/detalhar/5243); book codes 8 and 9 per the revoked [Provimento CNJ nº 3/2009, art. 7º](https://atos.cnj.jus.br/atos/detalhar/1310), still listed by [ghiorzi.org](http://ghiorzi.org/DVnew.htm) and [validation-br](https://github.com/klawdyo/validation-br/blob/feat-certidao/src/certidao.ts). ## CEI, CNO and CAEPF ### isValidCei Check if a CEI (Cadastro Específico do INSS) number is valid. The CEI identifies an employer with no CNPJ, such as a construction work or a rural producer. - Layout: 12 digits printed as `00.000.00000/00`, 11 base digits and one check digit. - A number loses its leading zeros, so a value that starts with `0` is only accepted as a string: `isValidCei('000000336854')` is `true` and `isValidCei(336854)` is `false`. - Only the 12 digits are official: no norm, layout or manual of the Receita Federal publishes the check digit, which follows the community references below and agrees with the CNO open dataset and with SERPRO's example `000000336854`. ```javascript import { isValidCei } from '@brazilian-utils/brazilian-utils'; isValidCei('11.583.00249/85'); // true isValidCei('277297118187'); // true isValidCei(249859674386); // true isValidCei(-249859674386); // false (not a non-negative safe integer) isValidCei('24.985.96743/68'); // false (invalid check digit) isValidCei('000000000000'); // false (repeated digits) ``` Source: [SERPRO, CNO cadastro](https://bcadastros.serpro.gov.br/documentacao/cadastro_cno/) (12 positions), [eSocial MOS S-1.3, item 9.1](https://www.gov.br/esocial/pt-br/documentacao-tecnica/manuais/mos-s-1-3-consolidada-ate-a-no-s-1-3-07-2026.pdf) (the CNO keeps the CEI number); check digit per [yii2-br-validator](https://github.com/yiibr/yii2-br-validator/blob/master/src/CeiValidator.php), [Bigai.Documentos.Brasil](https://github.com/marcos-cruz/Documento/blob/master/src/Bigai.Documentos.Brasil/Cei/Cei.cs) and the [CNO open dataset](https://dados.gov.br/dados/conjuntos-dados/cadastro-nacional-de-obras-cno). ### formatCei Format a CEI (Cadastro Específico do INSS) number with the usual `00.000.00000/00` mask. - **Options** (`FormatCeiOptions`): `pad` left-pads the value with zeros up to 12 digits (default `false`). An empty value, or one without digits, gives `''` even with `pad`. ```javascript import { formatCei } from '@brazilian-utils/brazilian-utils'; formatCei('277297118187'); // 27.729.71181/87 formatCei(249859674386); // 24.985.96743/86 formatCei('249', { pad: true }); // 00.000.00002/49 ``` ### parseCei Remove CEI (Cadastro Específico do INSS) formatting, keep only digits, and cap the result to 12 digits. ```javascript import { parseCei } from '@brazilian-utils/brazilian-utils'; parseCei('27.729.71181/87'); // '277297118187' ``` ### isValidCno Check if a CNO (Cadastro Nacional de Obras) number is valid. The CNO replaced the CEI for construction works and kept its numbering. - Same rules as `isValidCei`, the leading zeros of a number included. ```javascript import { isValidCno } from '@brazilian-utils/brazilian-utils'; isValidCno('11.084.01680/62'); // true isValidCno('111130137368'); // true isValidCno(401800097960); // true isValidCno(-401800097960); // false (not a non-negative safe integer) isValidCno('110840168063'); // false (invalid check digit) isValidCno('000000000000'); // false (repeated digits) ``` Source: [CNO page of the Receita Federal](https://www.gov.br/receitafederal/pt-br/assuntos/orientacao-tributaria/cadastros/cno), [SERPRO, CNO cadastro](https://bcadastros.serpro.gov.br/documentacao/cadastro_cno/), [eSocial MOS S-1.3, item 9.1](https://www.gov.br/esocial/pt-br/documentacao-tecnica/manuais/mos-s-1-3-consolidada-ate-a-no-s-1-3-07-2026.pdf) and the [CNO open dataset](https://dados.gov.br/dados/conjuntos-dados/cadastro-nacional-de-obras-cno). ### formatCno Format a CNO (Cadastro Nacional de Obras) number. - Same rules as `formatCei`: the `00.000.00000/00` mask, with `pad` in `FormatCnoOptions`. ```javascript import { formatCno } from '@brazilian-utils/brazilian-utils'; formatCno('111130137368'); // 11.113.01373/68 formatCno(401800097960); // 40.180.00979/60 formatCno('979', { pad: true }); // 00.000.00009/79 ``` ### parseCno Remove CNO (Cadastro Nacional de Obras) formatting, keep only digits, and cap the result to 12 digits, the numbering the CNO kept from the CEI. ```javascript import { parseCno } from '@brazilian-utils/brazilian-utils'; parseCno('11.113.01373/68'); // '111130137368' ``` ### isValidCaepf Check if a CAEPF (Cadastro de Atividade Econômica da Pessoa Física) number is valid. The CAEPF replaced the CEI for individuals who hire employees, such as rural producers. - Layout: 14 digits printed as `000.000.000/000-00`: the 9-digit CPF base of the holder, a 3-digit sequence and 2 check digits. - Both check digits follow the CNPJ's modulus 11; the pair is then shifted by 12, wrapping around 100. - A number loses its leading zeros, so a value that starts with `0` is only accepted as a string: `isValidCaepf('00000002500171')` is `true` and `isValidCaepf(2500171)` is `false`. - Only the 14 positions and the CPF base are official (SERPRO: "9 primeiros números do CPF + número de inscrição resumido" of 5 positions). The split of those 5 into a sequence and 2 check digits, the check digit rule and the shift of 12 come from the community references below; they agree with SERPRO's example `00000002500171`. ```javascript import { isValidCaepf } from '@brazilian-utils/brazilian-utils'; isValidCaepf('293.118.610/001-84'); // true isValidCaepf('41142260000101'); // true isValidCaepf(29311861000184); // true isValidCaepf(-29311861000184); // false (not a non-negative safe integer) isValidCaepf('29311861000185'); // false (invalid check digits) isValidCaepf('00000000000000'); // false (repeated base digits) isValidCaepf('00000000000012'); // false (repeated base digits) ``` Source: [SERPRO, CAEPF cadastro](https://bcadastros.serpro.gov.br/documentacao/cadastro_caepf/) (14 positions); check digits per [ghiorzi.org](http://ghiorzi.org/DVnew.htm) and [brazilian-values](https://github.com/VitorLuizC/brazilian-values/blob/master/src/validators/isCAEPF.ts). ### formatCaepf Format a CAEPF (Cadastro de Atividade Econômica da Pessoa Física) number with the usual `000.000.000/000-00` mask. - Same rules as `formatCei`, with `pad` (`FormatCaepfOptions`) padding up to 14 digits (default `false`). ```javascript import { formatCaepf } from '@brazilian-utils/brazilian-utils'; formatCaepf('29311861000184'); // 293.118.610/001-84 formatCaepf(41142260000101); // 411.422.600/001-01 formatCaepf('184', { pad: true }); // 000.000.000/001-84 ``` ### parseCaepf Remove CAEPF (Cadastro de Atividade Econômica da Pessoa Física) formatting, keep only digits, and cap the result to 14 digits. ```javascript import { parseCaepf } from '@brazilian-utils/brazilian-utils'; parseCaepf('293.118.610/001-84'); // '29311861000184' ``` ## Classification codes (CBO, CNAE, NCM, CFOP, CST, CSOSN) ### isValidCbo Check if a CBO (Classificação Brasileira de Ocupações) code exists in the official CBO 2002 table. - Accepts a string with the 6 digits or with the `NNNN-NN` mask, or a number. - A masked string may have any run of separators (space, `.`, `-` or `/`) between the groups. Any other string is rejected instead of having its digits picked out. - Bare digits are left padded with zeros to 6, as a string or as a number. A masked value is read as written. ```javascript import { isValidCbo } from '@brazilian-utils/brazilian-utils'; isValidCbo('2124-05'); // true isValidCbo('212405'); // true isValidCbo(212405); // true isValidCbo(10205); // true (padded to 6 digits, so this is '010205') isValidCbo('10205'); // true (padded the same way a number is) isValidCbo('000000'); // false isValidCbo('2124abc05'); // false (not a documented form) isValidCbo(-212405); // false (not a non-negative safe integer) ``` Source: [CBO 2002 tables published by the MTE ("Estrutura CBO (CSV)", files of 10/07/2026, 2,725 occupations)](https://cbo.mte.gov.br/cbosite/pages/downloads.jsf). ### formatCbo Format a CBO (Classificação Brasileira de Ocupações) code into the `NNNN-NN` mask. Only the structure changes; use `isValidCbo` to check a code against the table. - **Options** (`FormatCboOptions`): `pad` (default `false`) first left pads the value with zeros to the 6 digits of a complete code. Without it the mask is applied as far as the value goes. An empty value, or one without digits, gives `''` even with `pad`. - Characters outside the mask are dropped, and a number is read as the string of its digits only when it is a non-negative safe integer: a negative, fractional or unsafe number returns `''`. Returns `''` when there is no digit at all. ```javascript import { formatCbo } from '@brazilian-utils/brazilian-utils'; formatCbo('212405'); // 2124-05 formatCbo('21240'); // 2124-0 (masked as far as it goes) formatCbo('10205', { pad: true }); // 0102-05 (padded to 6 digits first) formatCbo('abc212405'); // 2124-05 (only the digits are read) formatCbo(-212405); // '' (not a non-negative safe integer) ``` Source: [CBO 2002 tables published by the MTE](https://cbo.mte.gov.br/cbosite/pages/downloads.jsf), which print the codes as `NNNN-NN`. ### parseCbo Remove CBO (Classificação Brasileira de Ocupações) formatting, keep only digits, and cap the result to 6 digits. - Nothing is left padded: the leading zero of a code such as `010205` has to be written out. Use `getCbo` or `isValidCbo` to look an occupation up. ```javascript import { parseCbo } from '@brazilian-utils/brazilian-utils'; parseCbo('2124-05'); // '212405' ``` ### getCbo Look a CBO (Classificação Brasileira de Ocupações) code up and get its official occupation title. The result is a `Cbo` record: `{ code, description }`. - Same rules as `isValidCbo`. Returns `null` when the code is unknown or the value is not in a documented form. ```javascript import { getCbo } from '@brazilian-utils/brazilian-utils'; getCbo('2124-05'); // { code: '212405', description: 'Analista de desenvolvimento de sistemas' } getCbo(10205); // { code: '010205', description: 'Oficial da aeronáutica' } (padded to 6 digits) getCbo('10205'); // { code: '010205', description: 'Oficial da aeronáutica' } (padded the same way) getCbo('000000'); // null getCbo('2124abc05'); // null (not a documented form) ``` Source: [CBO 2002 tables published by the MTE ("Estrutura CBO (CSV)", files of 10/07/2026, 2,725 occupations)](https://cbo.mte.gov.br/cbosite/pages/downloads.jsf). ### isValidCnae Check if a CNAE (Classificação Nacional de Atividades Econômicas) subclass code exists in the CNAE-Subclasses 2.3 table, the current subclass revision of CNAE 2.0. - Same rules as `isValidCbo`, with 7 digits and the `NNNN-N/NN` mask. ```javascript import { isValidCnae } from '@brazilian-utils/brazilian-utils'; isValidCnae('6201-5/01'); // true isValidCnae('6201501'); // true isValidCnae(111301); // true (padded to 7 digits, so this is '0111301') isValidCnae('111301'); // true (padded the same way a number is) isValidCnae('0000000'); // false isValidCnae('0111abc301'); // false (not a documented form) isValidCnae(-111301); // false (not a non-negative safe integer) ``` Source: [CNAE-Subclasses 2.3 at CONCLA/IBGE](https://concla.ibge.gov.br/busca-online-cnae.html) and the [IBGE subclasses API](https://servicodados.ibge.gov.br/api/v2/cnae/subclasses). ### formatCnae Format a CNAE (Classificação Nacional de Atividades Econômicas) subclass code. Only the structure changes; use `isValidCnae` to check a code against the table. - **Options** (`FormatCnaeOptions`): `pad` (default `false`) first left pads the value with zeros to the 7 digits of a complete code. Without it the mask is applied as far as the value goes. An empty value, or one without digits, gives `''` even with `pad`. - Characters outside the mask are dropped, and a number is read as the string of its digits only when it is a non-negative safe integer: a negative, fractional or unsafe number returns `''`, since its sign and decimal point are not mask characters. Returns `''` when there is no digit at all. ```javascript import { formatCnae } from '@brazilian-utils/brazilian-utils'; formatCnae('6201501'); // 6201-5/01 formatCnae('62'); // 62 (masked as far as it goes) formatCnae('62015'); // 6201-5 formatCnae('62', { pad: true }); // 0000-0/62 (padded to 7 digits first) formatCnae(111301, { pad: true }); // 0111-3/01 formatCnae('abc6201501'); // 6201-5/01 (only the digits are read) formatCnae(-6201501); // '' (not a non-negative safe integer) ``` ### parseCnae Remove CNAE (Classificação Nacional de Atividades Econômicas) formatting, keep only digits, and cap the result to the 7 digits of a complete subclass code. - Same rules as `parseCbo`: nothing is left padded here. ```javascript import { parseCnae } from '@brazilian-utils/brazilian-utils'; parseCnae('6201-5/01'); // '6201501' parseCnae('62'); // '62' (a partial code is kept as written) ``` ### getCnae Look a CNAE (Classificação Nacional de Atividades Econômicas) subclass code up and get its code and official description. The result is a `Cnae` record: `{ code, description }`. - Same rules as `getCbo`, with 7 digits and the `NNNN-N/NN` mask. - `code` comes back as the 7 bare digits; pass it to `formatCnae` for the `NNNN-N/NN` form. ```javascript import { formatCnae, getCnae } from '@brazilian-utils/brazilian-utils'; getCnae('6201-5/01'); // { code: '6201501', description: 'DESENVOLVIMENTO DE PROGRAMAS DE COMPUTADOR SOB ENCOMENDA' } getCnae(111301); // { code: '0111301', description: 'CULTIVO DE ARROZ' } (padded to 7 digits) getCnae('111301'); // { code: '0111301', description: 'CULTIVO DE ARROZ' } (padded the same way) getCnae('0000000'); // null getCnae('0111abc301'); // null (not a documented form) formatCnae(getCnae('6201501')?.code); // 6201-5/01 (the mask is the formatter's job) ``` Source: [CNAE-Subclasses 2.3 at CONCLA/IBGE](https://concla.ibge.gov.br/busca-online-cnae.html) and the [IBGE subclasses API](https://servicodados.ibge.gov.br/api/v2/cnae/subclasses). ### isValidNcm Check if an NCM (Nomenclatura Comum do Mercosul) code exists in the current table published by Siscomex/MDIC. - Same rules as `isValidCbo`, with 8 digits and the `NNNN.NN.NN` mask. ```javascript import { isValidNcm } from '@brazilian-utils/brazilian-utils'; isValidNcm('8471.30.12'); // true isValidNcm('84713012'); // true isValidNcm(1012100); // true (padded to 8 digits, so this is '01012100') isValidNcm('1012100'); // true (padded the same way a number is) isValidNcm('00000000'); // false isValidNcm('abc01012100'); // false (not a documented form) isValidNcm(-84713012); // false (not a non-negative safe integer) ``` Source: [NCM nomenclature published by the Portal Único Siscomex](https://portalunico.siscomex.gov.br/classif/api/publico/nomenclatura/download/json); the bundled 10,515 codes are those of the file "Vigente em 26/09/2026" (Resolução Gecex nº 926/2026). ### formatNcm Format an NCM (Nomenclatura Comum do Mercosul) code. Only the structure changes; use `isValidNcm` to check a code against the table. - **Options** (`FormatNcmOptions`): `pad` (default `false`) first left pads the value with zeros to the 8 digits of a complete code. An empty value, or one without digits, gives `''` even with `pad`. - Same rules as `formatCnae`, with the `NNNN.NN.NN` mask. ```javascript import { formatNcm } from '@brazilian-utils/brazilian-utils'; formatNcm('84713012'); // 8471.30.12 formatNcm('8471'); // 8471 (masked as far as it goes) formatNcm('847130'); // 8471.30 formatNcm('8471', { pad: true }); // 0000.84.71 (padded to 8 digits first) formatNcm('abc8471'); // 8471 (only the digits are read) formatNcm(-84713012); // '' (not a non-negative safe integer) ``` ### parseNcm Remove NCM (Nomenclatura Comum do Mercosul) formatting, keep only digits, and cap the result to the 8 digits of a complete code. - Same rules as `parseCbo`: nothing is left padded here. ```javascript import { parseNcm } from '@brazilian-utils/brazilian-utils'; parseNcm('8471.30.12'); // '84713012' parseNcm('8471'); // '8471' (a partial code is kept as written) ``` ### isValidNbs Check if an NBS (Nomenclatura Brasileira de Serviços, Intangíveis e Outras Operações que Produzam Variações no Patrimônio) code exists in the official NBS 2.0 table, the code the national NFS-e carries in `cNBS`. - A code has 9 digits, printed as `N.NNNN.NN.NN`: the digit 1, the chapter, the position, the two subposition levels, the item and the subitem. - Accepts a string with the 9 digits or with the mask, with any run of separators (space, `.`, `-` or `/`) between the groups and optional surrounding whitespace, or a non-negative safe integer. Any other string is rejected instead of having its digits picked out. - Only complete codes are valid: the chapter (`1.01`), position (`1.0101`) and subposition (`1.0101.1`) headings classify nothing by themselves. - The ANEXO B of the Sistema Nacional NFS-e lists the same 920 codes except three (`1.0402.29.00`, `1.0403.29.00` and `1.0904.40.00`), so a code valid here can still be refused by the NFS-e. ```javascript import { isValidNbs } from '@brazilian-utils/brazilian-utils'; isValidNbs('1.0101.11.00'); // true isValidNbs('101011100'); // true isValidNbs(101011100); // true isValidNbs('1.0101'); // false (a position heading, not a complete code) isValidNbs('1.9999.99.99'); // false isValidNbs('1.0101abc11.00'); // false (not a documented form) ``` ### formatNbs Format an NBS (Nomenclatura Brasileira de Serviços) code into the `N.NNNN.NN.NN` mask the nomenclature prints. Only the structure changes; use `isValidNbs` to check a code against the table. - **Options** (`FormatNbsOptions`): `pad` (default `false`) first left pads the value with zeros to the 9 digits of a complete code (every NBS code starts with 1, so it only serves a fixed width). An empty value, or one without digits, gives `''` even with `pad`. - Same rules as `formatCnae` otherwise: the mask is applied as far as the value goes, characters outside it are dropped, and a number is read as the string of its digits only when it is a non-negative safe integer; any other number returns `''`. ```javascript import { formatNbs } from '@brazilian-utils/brazilian-utils'; formatNbs('101011100'); // 1.0101.11.00 formatNbs(101011100); // 1.0101.11.00 formatNbs('10101'); // 1.0101 (masked as far as it goes) formatNbs('1', { pad: true }); // 0.0000.00.01 (padded to 9 digits first) formatNbs('abc101011100'); // 1.0101.11.00 (only the digits are read) formatNbs(-101011100); // '' (not a non-negative safe integer) ``` ### parseNbs Remove NBS (Nomenclatura Brasileira de Serviços) formatting, keep only digits, and cap the result to the 9 digits of a complete code. - Same rules as `parseCbo`: nothing is left padded here. ```javascript import { parseNbs } from '@brazilian-utils/brazilian-utils'; parseNbs('1.0101.11.00'); // '101011100' ``` ### getNbs Look an NBS (Nomenclatura Brasileira de Serviços) code up and get its official description. The result is an `Nbs` record: `{ code, description }`. - Same rules as `isValidNbs`. `code` is the 9 digits, without the mask. Returns `null` when the code is unknown or the value is not in a documented form. ```javascript import { getNbs } from '@brazilian-utils/brazilian-utils'; getNbs('1.0101.11.00'); // { code: '101011100', description: 'Serviços de construção de edificações residenciais de um e dois pavimentos' } getNbs(126050000); // { code: '126050000', description: 'Serviços domésticos' } getNbs('1.0101'); // null (a position heading, not a complete code) getNbs('1.9999.99.99'); // null ``` Source: [NBS 2.0 table published by the MDIC](https://www.gov.br/mdic/pt-br/assuntos/sdic/comercio-e-servicos/nbs-nomenclatura-brasileira-de-servicos), approved by the Portaria Conjunta RFB/SCS 1.429/2018 and amended by the Portaria Conjunta RFB/SCS 2.000/2018. ### isValidServiceItem Check if a value is a subitem in force of the service list annexed to the Lei Complementar 116/2003, the list of the services the ISS is levied on. - The law numbers a subitem as the item, a dot and two digits, `1.01` to `40.01`. - Accepts that form, a zero padded item (`'01.01'`) or the bare digits (`'0101'`, `'101'` or the integer `101`), which are the first four digits of the `cTribNac` code of the national NFS-e, with optional surrounding whitespace. - Any run of separators (space, `.`, `-` or `/`) is accepted between the item and the subitem, as in the other codes with a printed grouping mask (`isValidCfop`, `isValidNbs`), so `'1-01'` and `'1 01'` are valid too. - A number is only read when it is a non-negative safe integer, so the float `1.01` is rejected: write the dotted form as a string. - The vetoed subitems (`3.01`, `7.14`, `7.15`, `13.01` and `17.07`), the item headings, the 6 digit national codes a subitem is split into and item 99 of the national list, which is not part of the law, are not valid. Municipal service codes are out of scope. ```javascript import { isValidServiceItem } from '@brazilian-utils/brazilian-utils'; isValidServiceItem('1.01'); // true isValidServiceItem('01.01'); // true isValidServiceItem('0101'); // true isValidServiceItem(101); // true isValidServiceItem('3.01'); // false (vetoed) isValidServiceItem('99.01'); // false (national list only, not the law) isValidServiceItem(1.01); // false (not a non-negative safe integer) ``` ### getServiceItem Look a subitem of the service list annexed to the Lei Complementar 116/2003 up and get its official description. The result is a `ServiceItem` record: `{ code, description }`. - Same rules as `isValidServiceItem`. `code` is the form the law prints (`'1.01'`). Returns `null` when the subitem is unknown or the value is not in a documented form. ```javascript import { getServiceItem } from '@brazilian-utils/brazilian-utils'; getServiceItem('1.01'); // { code: '1.01', description: 'Análise e desenvolvimento de sistemas.' } getServiceItem('0101'); // { code: '1.01', description: 'Análise e desenvolvimento de sistemas.' } getServiceItem('40.01'); // { code: '40.01', description: 'Obras de arte sob encomenda.' } getServiceItem('3.01'); // null (vetoed) ``` Source: [Lei Complementar 116/2003](https://www.planalto.gov.br/ccivil_03/leis/lcp/lcp116.htm), whose list was last amended by Lei Complementar 183/2021, and the sheet `LISTA.SERV.NAC.` of the [ANEXO B of the Sistema Nacional NFS-e](https://www.gov.br/nfse/pt-br/biblioteca/documentacao-tecnica/documentacao-atual), the list in force in machine readable form. ### isValidCfop Check if a CFOP (Código Fiscal de Operações e Prestações) code exists in the official table, the consolidated Anexo II of Convênio SINIEF s/nº 1970 in force. - Only operable codes count: the group and subgroup headings, the codes ending in `00` and `50`, are rejected. - Accepts a string with the 4 digits or with the `N.NNN` form, with any run of separators (space, `.`, `-` or `/`) between the groups, or a number. Any other string is rejected. - No CFOP code starts with a zero, so nothing is padded. ```javascript import { isValidCfop } from '@brazilian-utils/brazilian-utils'; isValidCfop('5102'); // true isValidCfop('1.101'); // true isValidCfop('7504'); // true (added by the 2022 rewrite of the annex) isValidCfop('0000'); // false isValidCfop('1150'); // false (a subgroup heading, not an operable code) isValidCfop('abc5102'); // false (not a documented form) isValidCfop(-5102); // false (not a non-negative safe integer) ``` Source: [consolidated Anexo II of Convênio SINIEF s/nº 1970](https://www.confaz.fazenda.gov.br/legislacao/ajustes/sinief/cfop_cvsn_1-6.24), last amended by [Ajuste SINIEF 39/25](https://www.confaz.fazenda.gov.br/legislacao/ajustes/2025/AJ039_25). ### formatCfop Format a CFOP (Código Fiscal de Operações e Prestações) code into the `N.NNN` form the annex prints. Only the structure changes; use `isValidCfop` to check a code against the table. - **Options** (`FormatCfopOptions`): `pad` (default `false`) first left pads the value with zeros to the 4 digits of a complete code (no CFOP starts with a zero, so it only serves a fixed width). Without it the mask is applied as far as the value goes. An empty value, or one without digits, gives `''` even with `pad`. - Characters outside the mask are dropped, and a number is read as the string of its digits only when it is a non-negative safe integer: a negative, fractional or unsafe number returns `''`. Returns `''` when there is no digit at all. ```javascript import { formatCfop } from '@brazilian-utils/brazilian-utils'; formatCfop('5102'); // 5.102 formatCfop('51'); // 5.1 (masked as far as it goes) formatCfop('102', { pad: true }); // 0.102 (padded to 4 digits first) formatCfop('abc5102'); // 5.102 (only the digits are read) formatCfop(-5102); // '' (not a non-negative safe integer) ``` Source: [Convênio SINIEF s/nº 1970, Anexo II](https://www.confaz.fazenda.gov.br/legislacao/ajustes/sinief/cfop_cvsn_1-6.24), which prints the codes as `N.NNN`. ### parseCfop Remove CFOP (Código Fiscal de Operações e Prestações) formatting, keep only digits, and cap the result to 4 digits. - No CFOP code starts with a zero, so nothing is padded here. ```javascript import { parseCfop } from '@brazilian-utils/brazilian-utils'; parseCfop('5.102'); // '5102' ``` ### getCfop Look a CFOP (Código Fiscal de Operações e Prestações) code up and get its code and official description. The result is a `Cfop` record: `{ code, description }`. - Same rules as `isValidCfop`. Returns `null` for a heading, an unknown code or a value not in a documented form. ```javascript import { getCfop } from '@brazilian-utils/brazilian-utils'; getCfop('1101'); // { code: '1101', description: 'Compra para industrialização ou produção rural' } getCfop('7504'); // { code: '7504', description: 'Exportação de mercadoria que foi objeto de formação de lote de exportação' } getCfop('0000'); // null getCfop('5350'); // null (a subgroup heading, not an operable code) getCfop('abc5102'); // null (not a documented form) ``` Source: [consolidated Anexo II of Convênio SINIEF s/nº 1970](https://www.confaz.fazenda.gov.br/legislacao/ajustes/sinief/cfop_cvsn_1-6.24), last amended by [Ajuste SINIEF 39/25](https://www.confaz.fazenda.gov.br/legislacao/ajustes/2025/AJ039_25). ### isValidCest Check if a CEST (Código Especificador da Substituição Tributária) is listed in the annexes of Convênio ICMS 142/18, the consolidated text in force. - Only the items in force count: an item the annexes mark as revoked is rejected. - The check is about the code alone: it does not tell whether the code suits a given NCM, nor whether a state applies the substituição tributária regime to it. - A CEST has 7 digits: the first two are the segment, the third to the fifth the item of the segment and the last two the specification of the item (cláusula sexta, IV). - Accepts a string with the 7 digits or with the `NN.NNN.NN` form the annexes print, with any run of separators (space, `.`, `-` or `/`) between the groups and optional surrounding whitespace, or a non-negative safe integer. Any other string is rejected instead of having its digits picked out. - The leading zero of segments 01 to 09 is part of the code, so a value written as bare digits is left padded with zeros to 7, as a string or as a number: `100100`, `'100100'` and `'0100100'` are the same code. A masked value is read as written. ```javascript import { isValidCest } from '@brazilian-utils/brazilian-utils'; isValidCest('01.001.00'); // true isValidCest('0100100'); // true isValidCest(100100); // true (padded to 7 digits, so this is '0100100') isValidCest('03.001.00'); // false (a revoked item) isValidCest('0000000'); // false isValidCest('abc0100100'); // false (not a documented form) isValidCest(-100100); // false (not a non-negative safe integer) ``` ### formatCest Format a CEST (Código Especificador da Substituição Tributária) in the `NN.NNN.NN` form the annexes of Convênio ICMS 142/18 print. Only the structure changes; use `isValidCest` to check a code against the annexes. - **Options** (`FormatCestOptions`): `pad` (default `false`) first left pads the value with zeros to the 7 digits of a complete code. An empty value, or one without digits, gives `''` even with `pad`. - Same rules as `formatNcm`: without `pad` the mask is applied as far as the value goes, which is what an input being typed into needs, characters outside it are dropped, and a number is read as the string of its digits, so it is only padded under `pad: true`. A number is only read when it is a non-negative safe integer; any other number returns `''`. ```javascript import { formatCest } from '@brazilian-utils/brazilian-utils'; formatCest('0100100'); // 01.001.00 formatCest(2899900); // 28.999.00 formatCest('01001'); // 01.001 (masked as far as it goes) formatCest(100100, { pad: true }); // 01.001.00 (padded to 7 digits first) formatCest('abc0100100'); // 01.001.00 (only the digits are read) formatCest(-2899900); // '' (not a non-negative safe integer) ``` ### parseCest Remove CEST (Código Especificador da Substituição Tributária) formatting, keep only digits, and cap the result to the 7 digits of a complete code. - Same rules as `parseCbo`: nothing is left padded here, so the leading zero of segments 01 to 09 has to be written out. Use `isValidCest` or `getCest`, which do pad a bare numeric code, to look a code up. ```javascript import { parseCest } from '@brazilian-utils/brazilian-utils'; parseCest('01.001.00'); // '0100100' parseCest('28.999'); // '28999' (a partial code is kept as written) ``` ### getCest Look a CEST (Código Especificador da Substituição Tributária) up and get the description of the goods and the name of its segment, as Anexos I to XXVI of Convênio ICMS 142/18 word them. The result is a `Cest` record: `{ code, description, segment }`. - Same rules as `isValidCest`. Returns `null` for an unknown, revoked or malformed code. - The NCM/SH codes the annexes pair each CEST with are not part of the entry. ```javascript import { getCest } from '@brazilian-utils/brazilian-utils'; getCest('05.001.00'); // { code: '0500100', description: 'Cimento', segment: 'Cimentos' } getCest(500100); // { code: '0500100', description: 'Cimento', segment: 'Cimentos' } getCest('03.001.00'); // null (a revoked item) getCest('0000000'); // null getCest('abc0500100'); // null (not a documented form) ``` Source: [consolidated Convênio ICMS 142/18](https://www.confaz.fazenda.gov.br/legislacao/convenios/2018/CV142_18), last amended by Convênio ICMS 180/24. ### isValidCst Check if a CST (Código de Situação Tributária) code is valid for a given tax. Pass the tax through `options.tax`: | Tax | Format | Accepted codes | | --- | --- | --- | | `icms` | 2 digits (Tabela B) or 3 digits (origem + CST) | the Tabela B code alone, or origem `0`-`8` + one of `00`, `02`, `10`, `15`, `20`, `30`, `40`, `41`, `50`, `51`, `53`, `60`, `61`, `70`, `90` | | `ipi` | 2 digits | `00`, `01`, `02`, `03`, `04`, `05`, `49`, `50`, `51`, `52`, `53`, `54`, `55`, `99` | | `pis` | 2 digits | `01`-`09`, `49`, `50`-`56`, `60`-`67`, `70`-`75`, `98`, `99` | | `cofins` | 2 digits | same table as `pis` | - **Options** (`IsValidCstOptions`): `tax` picks the table. Omitted, or outside those four values, every table is accepted; a `null` or non-object `options` is read as none. - Accepts a string with the 2 digits of a Tabela B code or the 3 digits of the ICMS form, or a number. The ICMS form may have any run of separators (space, `.`, `-` or `/`) after the origin digit. - A single digit is padded to the 3-digit ICMS form; a 2-digit value is a Tabela B code and is never read as an origin plus a digit (`'10'` is the Tabela B code `10`), while the number `7` is read as the ICMS code `007`, which is not in the table, so it is `false`. ```javascript import { isValidCst } from '@brazilian-utils/brazilian-utils'; isValidCst('000', { tax: 'icms' }); // true isValidCst(0, { tax: 'icms' }); // true (a single digit is padded to the 3 digit form, '000') isValidCst('0', { tax: 'icms' }); // true (padded the same way a number is) isValidCst('110', { tax: 'icms' }); // true isValidCst('002', { tax: 'icms' }); // true (monofasia de combustíveis) isValidCst('60', { tax: 'icms' }); // true (a bare Tabela B code, as the NF-e CST field carries it) isValidCst('06', { tax: 'pis' }); // true isValidCst('99', { tax: 'ipi' }); // true isValidCst('110'); // true (found in the icms table, tax omitted) isValidCst('000', { tax: 'nope' }); // true (an unknown tax falls back to every table) isValidCst('999'); // false (not in any table) isValidCst('abc110'); // false (not a documented form) isValidCst(-110); // false (not a non-negative safe integer) ``` Source: ICMS Tabela B from [Anexo I of Convênio SINIEF s/nº 1970](https://www.confaz.fazenda.gov.br/legislacao/ajustes/sinief/cvsn_70) as amended by [Ajuste SINIEF 20/24](https://www.confaz.fazenda.gov.br/legislacao/ajustes/2024/AJ020_24); IPI, PIS and COFINS from [IN RFB nº 1.009/2010](https://normas.receita.fazenda.gov.br/sijut2consulta/link.action?idAto=15974). ### isValidCsosn Check if a CSOSN (Código de Situação da Operação no Simples Nacional) code is one of the 10 codes of the official table: `101`, `102`, `103`, `201`, `202`, `203`, `300`, `400`, `500` or `900`. - Accepts a string with the bare 3 digits, or a number. A CSOSN has no printed grouping, so `'1-01'` is rejected. ```javascript import { isValidCsosn } from '@brazilian-utils/brazilian-utils'; isValidCsosn('101'); // true isValidCsosn(900); // true isValidCsosn('999'); // false isValidCsosn('abc101'); // false (not a documented form) isValidCsosn(-101); // false (not a non-negative safe integer) ``` Source: [consolidated Anexo III-A of Convênio SINIEF s/nº 1970](https://www.confaz.fazenda.gov.br/legislacao/ajustes/sinief/cvsn_70) and [Ajuste SINIEF 03/2010](https://www.confaz.fazenda.gov.br/legislacao/ajustes/2010/aj_003_10). ### isValidCstIbsCbs Check if a CST-IBS/CBS (Código de Situação Tributária do IBS e da CBS) exists in the official table, the code the field `CST` of the group `IBSCBS` carries in the electronic fiscal documents of the tax reform (Lei Complementar nº 214/2025): NF-e, NFC-e, CT-e, NFS-e and the others. - The codes in force are `000`, `010`, `011`, `200`, `220`, `221`, `222`, `400`, `410`, `510`, `515`, `550`, `620`, `800`, `810`, `811`, `820` and `830`. - It is a function of its own, not a `tax` of `isValidCst`: IBS and CBS share one table, its 3 digit codes collide with the ICMS origin plus Tabela B form (`000`, `200`), and `isValidCst` without a `tax` accepts a code of any table, so adding this one would change what that default accepts. - Accepts a string of bare digits with optional surrounding whitespace, or a non-negative safe integer. The field is numeric with 3 digits and has no mask, so any other string is rejected instead of having its digits picked out. - A value narrower than 3 digits is left padded with zeros, as a string or as a number, since the codes start with zeros a numeric field drops: `0`, `'0'` and `'000'` are all the code `000`. ```javascript import { isValidCstIbsCbs } from '@brazilian-utils/brazilian-utils'; isValidCstIbsCbs('000'); // true isValidCstIbsCbs(410); // true isValidCstIbsCbs(10); // true (padded to '010') isValidCstIbsCbs('100'); // false isValidCstIbsCbs('cst200'); // false (not a documented form) isValidCstIbsCbs(-200); // false (not a non-negative safe integer) ``` ### getCstIbsCbs Look a CST-IBS/CBS up and get the description the official CST table gives it. The result is a `CstIbsCbs` record: `{ code, description }`. - Same table and input rules as `isValidCstIbsCbs`. Returns `null` when the code is unknown or the value is not in a documented form. ```javascript import { getCstIbsCbs } from '@brazilian-utils/brazilian-utils'; getCstIbsCbs('000'); // { code: '000', description: 'Tributação integral' } getCstIbsCbs(410); // { code: '410', description: 'Imunidade e não incidência' } getCstIbsCbs(10); // { code: '010', description: 'Tributação com alíquotas uniformes' } getCstIbsCbs('100'); // null getCstIbsCbs('cst200'); // null (not a documented form) ``` ### isValidClassTrib Check if a cClassTrib (Código de Classificação Tributária do IBS e da CBS) exists in the official table, the code the field `cClassTrib` carries next to the CST-IBS/CBS. - **Options** (`IsValidClassTribOptions`): `cst` is the CST-IBS/CBS the document carries, checked against the classification as well. Omit it to check the cClassTrib alone; a `null` or non-object `options` is read as none. - Every classification belongs to exactly one CST-IBS/CBS, the first 3 digits of its code, and a document that carries a cClassTrib with another CST is rejected (rejection 1024, "Classificação Tributária do IBS e da CBS incompatível com o CST informado"). A `cst` that is given and is not the CST of the classification, whatever it is, makes the result `false`. - Only the classifications in force count: the Informe Técnico 2025.002 excludes a classification by closing its validity (`dFimVig`), as v.1.60 did with `220001`, `220002` and `220003`, and those are rejected. 161 are in force in the version published on 23/06/2026. - Accepts a string of bare digits with optional surrounding whitespace, or a non-negative safe integer. The field is numeric with 6 digits and has no mask, so any other string is rejected. - A value narrower than 6 digits is left padded with zeros: `1`, `'1'` and `'000001'` are all the code `000001`. `cst` is read the same way, padded to 3 digits. - Only the code list is bundled with this function, not the descriptions `getClassTrib` returns. ```javascript import { isValidClassTrib } from '@brazilian-utils/brazilian-utils'; isValidClassTrib('200001'); // true isValidClassTrib(1); // true (padded to '000001') isValidClassTrib('200001', { cst: '200' }); // true isValidClassTrib('200001', { cst: '000' }); // false (the classification belongs to CST 200) isValidClassTrib('999999'); // false isValidClassTrib('220001'); // false (excluded by Informe Técnico 2025.002 v.1.60) isValidClassTrib('c200001'); // false (not a documented form) ``` ### getClassTrib Look a cClassTrib up and get its official classification. The result is a `ClassTrib` record: `{ code, cst, name, description }`. - Same table and the same rules for reading the code as `isValidClassTrib`. Returns `null` when the code is unknown or the value is not in a documented form. - The `cst` option exists only on `isValidClassTrib`, since the entry returned here already carries its CST as `cst`. - `cst` is the CST-IBS/CBS the classification belongs to, the first 3 digits of its code; `name` is the short name the official table gives for display (the column "Nome cClassTrib") and `description` the situation it refers to (the column "Descrição cClassTrib"). - The legal wording the workbook also prints for each row (the article of Lei Complementar nº 214/2025 and of both regulations) is not shipped. ```javascript import { getClassTrib } from '@brazilian-utils/brazilian-utils'; getClassTrib('000002'); // { // code: '000002', // cst: '000', // name: 'Exploração de via', // description: 'Exploração de via, observado o art. 11 da Lei Complementar nº 214, de 2025.', // } getClassTrib(2)?.code; // '000002' getClassTrib('999999'); // null getClassTrib('220001'); // null (excluded by Informe Técnico 2025.002 v.1.60) getClassTrib('c200001'); // null (not a documented form) ``` Source: the CST and cClassTrib sheets of the "Tabela de Classificação Tributária do IBS e CBS" workbook the [Portal Nacional da NF-e publishes under "Documentos" > "Diversos"](https://www.nfe.fazenda.gov.br/portal/listaConteudo.aspx?tipoConteudo=/NJarYc9nus=) (the version published on 23/06/2026), divulged by the [Informe Técnico 2025.002](https://www.nfe.fazenda.gov.br/portal/listaConteudo.aspx?tipoConteudo=hXzemuyNHW4=) (v.1.60), and the [Nota Técnica 2025.002-RTC](https://www.nfe.fazenda.gov.br/portal/listaConteudo.aspx?tipoConteudo=04BIflQt1aY=), fields UB13 and UB14. ## GTIN (product barcode) ### isValidGtin Check if a GTIN (Global Trade Item Number, the number under an EAN/UPC barcode) is valid. - Covers the four structures of the GS1 General Specifications, the same four the NF-e accepts in `cEAN` and `cEANTrib`: GTIN-8, GTIN-12 (UPC), GTIN-13 (EAN) and GTIN-14 (DUN-14). - **Options** (`IsValidGtinOptions`): `lengths` accepts only some of the four lengths, and defaults to all four. - The value must be a string of 8, 12, 13 or 14 digits, surrounding whitespace aside, whose last digit is the GS1 modulo 10 check digit: weights 3 and 1 alternating from the right, the sum subtracted from the nearest equal or higher multiple of ten. That is what rules I03-10 and I12-10 of SEFAZ Nota Técnica 2021.003 check (rejections 611 and 612). - Leading zeros count, so a number is never accepted, and a masked value (`'7 890000 000017'`) is rejected instead of having its digits picked out. - The `'SEM GTIN'` literal the NF-e uses for a product without a GTIN is not a GTIN, so it is not valid here: test for it before calling. - A value of zeros only is rejected, although its check digit is valid. That is a rule of this library, not of the NF-e or GS1: rejection 611 is only the check digit, and the GS1 General Specifications (release 26.0, table 1-4) reserve the GS1 Prefix `0000000` for Restricted Circulation Numbers within a company rather than forbid it. Zeros are rejected as the usual placeholder for a missing GTIN. - The prefix does not change the verdict. Restricted Circulation Numbers (prefixes 02, 04 and 20 to 29, the codes a shop prints on its own scale labels) and the ISSN, ISBN and coupon ranges share the structure and the check digit, and the "Tabela Prefixo GS1" SEFAZ validates `cEAN` against lists them as valid; use `getGtinInfo` to tell them apart. - The prefix is not checked against the list of GS1 Member Organisations either: GS1 keeps assigning ranges, so a copy of that list would turn down valid numbers as it ages. Whether the number is registered (the Cadastro Centralizado de GTIN lookup SEFAZ runs for the 789 and 790 prefixes) cannot be checked offline. ```javascript import { isValidGtin } from '@brazilian-utils/brazilian-utils'; isValidGtin('7890000000017'); // true (GTIN-13, GS1 Brasil prefix) isValidGtin('6291041500213'); // true (the example of the GS1 check digit page) isValidGtin('78912342'); // true (GTIN-8) isValidGtin('061414112345'); // true (GTIN-12) isValidGtin('17890000000014'); // true (GTIN-14) isValidGtin('7890000000018'); // false (wrong check digit) isValidGtin('17890000000014', { lengths: [8, 12, 13] }); // false (GTIN-14 not accepted) isValidGtin('7 890000 000017'); // false (digits only) isValidGtin('SEM GTIN'); // false isValidGtin('0000000000000'); // false (zeros only, a rule of this library) ``` ### getGtinInfo Parse a GTIN into its fields, as a `GtinInfo`. - Returns `null` when the value is not a valid GTIN, under the same rules as `isValidGtin`. - The prefix is read as the GS1 General Specifications (tables 1-4, 1-5 and 1-9) lay the numbers out: the value is left padded with zeros to 14 digits, and the prefix is positions 7 to 9 when positions 2 to 6 are zeros (a GTIN-8, or a GTIN-14 that packs one) and positions 2 to 4 otherwise. The first digit, the padding zero or the indicator digit, is never part of the prefix, so a GTIN-12 has a prefix that starts with `0`, and a GTIN-14 has the prefix of the GTIN it packs. | Field | Description | | --- | --- | | `type` | `'GTIN-8'`, `'GTIN-12'`, `'GTIN-13'` or `'GTIN-14'` (`GtinType`), from the length the value was written with | | `length` | `8`, `12`, `13` or `14` (`GtinLength`) | | `prefix` | The three digit GS1 Prefix, or a GS1-8 Prefix when positions 2 to 6 of the 14 digit form are zeros, which covers every GTIN-8, a GTIN-14 that packs one and the GS1 Prefix `0000000`. It names the GS1 Member Organisation that licensed the number, not the country of origin | | `isBrazilian` | `true` when the prefix is one of GS1 Brasil, `789` or `790`, what NT 2021.003 calls "prefixo do Brasil" | | `isRestrictedCirculation` | `true` when the prefix is in a range GS1 sets aside for Restricted Circulation Numbers (GS1 Prefixes 02, 04 and 20 to 29; GS1-8 Prefixes 000 to 099 and 200 to 299, which is also where the GS1 Prefix `0000000` lands, since its 14 digit form starts with six zeros), so the number is only unique inside a company or region | | `checkDigit` | The modulo 10 check digit, the last digit | ```javascript import { getGtinInfo } from '@brazilian-utils/brazilian-utils'; getGtinInfo('7890000000017'); // { type: 'GTIN-13', length: 13, prefix: '789', isBrazilian: true, // isRestrictedCirculation: false, checkDigit: 7 } getGtinInfo('17890000000014'); // { type: 'GTIN-14', length: 14, prefix: '789', isBrazilian: true, // isRestrictedCirculation: false, checkDigit: 4 } getGtinInfo('061414112345'); // { type: 'GTIN-12', length: 12, prefix: '006', isBrazilian: false, // isRestrictedCirculation: false, checkDigit: 5 } getGtinInfo('2000000000015')?.isRestrictedCirculation; // true (in-store number) getGtinInfo('7890000000018'); // null (wrong check digit) ``` Source: [GS1 General Specifications](https://ref.gs1.org/standards/genspecs/), [GS1 check digit calculator](https://www.gs1.org/services/how-calculate-check-digit-manually), [SEFAZ Nota Técnica 2021.003](https://www.nfe.fazenda.gov.br/portal/exibirArquivo.aspx?conteudo=SrQT9ys8ODo%3D) and the [Tabela Prefixo GS1](https://www.nfe.fazenda.gov.br/portal/exibirArquivo.aspx?conteudo=Oc+fygAxwmc%3D) of the Portal da NF-e. ## ISBN The ISBN (International Standard Book Number) has 13 digits since 2007: the GS1 prefix (`978`, or `979` for the newer ranges), the registration group (`85` and `65` for Brazil), the registrant (the publisher), the publication and a check digit. The 10 digit ISBN is not accepted: the current ISBN Users' Manual (7th edition) and the Agência Brasileira do ISBN only define the 13 digit form. ### isValidIsbn Check if an ISBN-13 is valid: the `978` or `979` prefix and the modulus 10 check digit of the ISBN Users' Manual (the first 12 digits weighed alternately 1 and 3, the same rule as a GTIN-13). - Separators between two digits (space, `.`, `-` or `/`, alone or in a run, as `isValidCpf` reads its mask) and spaces around the value are accepted; anything else, a leading or trailing separator or the `ISBN` label a book prints in front of the number included, makes the value invalid. - A `979-0` number is an ISMN (printed music), not an ISBN: the RangeMessage gives that range no ISBN group, so it is rejected. - Whether the group and the registrant are assigned is not checked; see `getIsbnInfo`. - The printed example of the Agência Brasileira do ISBN, `ISBN 978-65-89999-01-3`, does not carry the check digit the rule gives (`0`), so it is rejected. ```javascript import { isValidIsbn } from '@brazilian-utils/brazilian-utils'; isValidIsbn('9788533302273'); // true isValidIsbn('978-65-89999-01-0'); // true isValidIsbn('978-85-333-0227-4'); // false (wrong check digit) isValidIsbn('8533302276'); // false (the 10 digit form) ``` ### parseIsbn Remove the hyphens and every other character that is not a digit, keeping at most 13 digits. ```javascript import { parseIsbn } from '@brazilian-utils/brazilian-utils'; parseIsbn('978-85-333-0227-3'); // '9788533302273' ``` ### getIsbnInfo Split a valid ISBN-13 into its elements, as an `IsbnInfo`, following the ranges the International ISBN Agency publishes (the RangeMessage), which give the variable lengths of the group and of the registrant. - Returns `null` when the value is not valid under `isValidIsbn`, or when its group or registrant falls in a range not assigned yet. - The ranges are refreshed by the datasets workflow. | Field | Description | | --- | --- | | `isbn` | The 13 digits | | `prefix` | `'978'` or `'979'` | | `registrationGroup` | The country, region or language area, e.g. `'85'` or `'65'` for Brazil | | `registrant` | The publisher or imprint within the group | | `publication` | The edition within the registrant | | `checkDigit` | The check digit, the last digit | | `agency` | The agency the International ISBN Agency lists for the group, e.g. `'Brazil'` or `'English language'` | | `isBrazilian` | `true` for the groups of the Agência Brasileira do ISBN, `85` and `65` | ```javascript import { getIsbnInfo } from '@brazilian-utils/brazilian-utils'; getIsbnInfo('978-65-89999-01-0'); // { isbn: '9786589999010', prefix: '978', registrationGroup: '65', registrant: '89999', // publication: '01', checkDigit: 0, agency: 'Brazil', isBrazilian: true } getIsbnInfo('9780306406157')?.agency; // 'English language' ``` ### formatIsbn Hyphenate an ISBN-13 by its elements, as `getIsbnInfo` splits it. The element lengths vary, so a partial or invalid value, or one in a range not assigned yet, returns `''`. The `ISBN` label is not added. ```javascript import { formatIsbn } from '@brazilian-utils/brazilian-utils'; formatIsbn('9788533302273'); // '978-85-333-0227-3' formatIsbn('9780306406157'); // '978-0-306-40615-7' formatIsbn('978853330227'); // '' ``` Source: [ISBN Users' Manual, 7th edition](https://www.isbn-international.org/content/isbn-users-manual/29), [ISBN Ranges (RangeMessage)](https://www.isbn-international.org/range_file_generation) of the International ISBN Agency, and the [Agência Brasileira do ISBN](https://www.cblservicos.org.br/isbn/estrutura/). ## CID-10 ### isValidCid10 Check if a CID-10 code exists in the tables DATASUS publishes, the Brazilian Portuguese edition of the ICD-10 (Classificação Estatística Internacional de Doenças e Problemas Relacionados à Saúde, 10th revision), the code medical certificates and health systems carry. - Both levels of the classification are valid: the 3 character categories (`A00`) and the 4 character subcategories, written with the dot (`A00.0`) or without it (`A000`). - Letter case and surrounding whitespace are ignored. Anything else (another separator, a fifth character, a dagger or asterisk suffix, a value that is not a string) is rejected. - The tables are the DATASUS V2008 ones, plus the `U07` category of the CID-10 table DATASUS keeps for the SIM (`U07`, `U07.0`, `U07.1` COVID-19 virus identified and `U07.2` virus not identified), which the V2008 files predate. A code in neither is not found, such as `U09.9` (post COVID-19 condition) and `U10.9` (multisystem inflammatory syndrome associated with COVID-19). Up to 2.4.0 the `U07` codes were not found either. - Only a table of codes is read (about 7 KB minified), not the descriptions `getCid10` carries. ```javascript import { isValidCid10 } from '@brazilian-utils/brazilian-utils'; isValidCid10('A00.0'); // true isValidCid10('a000'); // true isValidCid10('A00'); // true (a category) isValidCid10('I10'); // true (a category that is not subdivided) isValidCid10('A00.5'); // false (A00 has no subcategory 5) isValidCid10('I10.0'); // false (I10 has no subcategories) isValidCid10('A00-0'); // false (not a documented form) ``` ### formatCid10 Format a CID-10 code the way it is printed: upper case, with a dot between the 3 character category and the fourth character of the subcategory. Only the structure changes; use `isValidCid10` to check a code against the tables. - The mask is applied as far as the value goes, so a category stays as it is and the dot only shows up with the fourth character. - Characters outside the mask are dropped and the value is capped at 4 characters. ```javascript import { formatCid10 } from '@brazilian-utils/brazilian-utils'; formatCid10('A000'); // A00.0 formatCid10('f322'); // F32.2 formatCid10('A00'); // A00 (a category has no dot) formatCid10('A00.0'); // A00.0 ``` ### parseCid10 Remove CID-10 formatting, keep only letters and digits, upper case them and cap the result to the 4 characters of a subcategory, the form the DATASUS tables store. - A shorter value passes through as far as it goes. ```javascript import { parseCid10 } from '@brazilian-utils/brazilian-utils'; parseCid10('A00.0'); // 'A000' parseCid10('f32.2'); // 'F322' parseCid10('A00'); // 'A00' ``` ### getCid10 Look a CID-10 code up and get its official Brazilian Portuguese description. The result is a `Cid10` record: `{ code, description }`. - Same input rules as `isValidCid10`. `code` is upper case and has no dot. Returns `null` when the code is unknown or the value is not in a documented form. - Same table as `isValidCid10`: the DATASUS V2008 one plus the `U07` codes of the SIM table (`getCid10('U07.1')` is `{ code: 'U071', description: 'Infecção pelo novo Coronavírus (COVID-19)' }`); `U09.9` and `U10.9` are not found. - This is the heaviest util of the package: it embeds the 2046 categories and 12191 subcategories with their descriptions, about 722 KB minified (113 KB gzipped). Load it lazily through its subpath, as shown in [Bundle size](getting-started.md#bundle-size), and use `isValidCid10` when the description is not needed. ```javascript import { getCid10 } from '@brazilian-utils/brazilian-utils'; getCid10('A00.0'); // { code: 'A000', description: 'Cólera devida a Vibrio cholerae 01, biótipo cholerae' } getCid10('a000'); // { code: 'A000', description: 'Cólera devida a Vibrio cholerae 01, biótipo cholerae' } getCid10('A00'); // { code: 'A00', description: 'Cólera' } getCid10('A00.5'); // null getCid10('A00-0'); // null (not a documented form) ``` Source: [CID-10 V2008 tables DATASUS publishes as CSV](http://www2.datasus.gov.br/cid10/V2008/descrcsv.htm) and the [CID-10 table of the SIM](ftp://ftp.datasus.gov.br/dissemin/publicos/SIM/CID10/TABELAS/CID10.DBF) for the `U07` codes. ## Text ### capitalize Capitalize the first letter of each word, the way a Brazilian name, company name or address is written, with no options needed. - **Options** (`CapitalizeOptions`): `lowerCaseWords`, words kept in lower case between two words, by default the prepositions and the conjunction `e`, such as `de`, `da`, `do`, `ao`, `para`, `pelo`, `sobre`, `até` (the articles are only `a` and `o`); `upperCaseWords`, words always in upper case, by default company designations and abbreviations such as `LTDA`, `S.A.`, `ME`, `CNPJ` and roman numerals. A list replaces its default. - Words split at whitespace, `-`, `/`, apostrophes and adjoining punctuation; whitespace runs collapse into one space. - A lower-case word that is first, last or followed by punctuation is a designator and keeps its capital. - `ME` is upper-cased only as a designation (last word, or before another designation); `S.A` without the final dot is a designation too, while `SA` without dots is left alone (the surname Sá). A state code after a `/` is upper-cased even with `upperCaseWords` given, and so is one that ends the value after a spaced `-`, a spaced `–` or a `, `, the Correios' "Cidade – UF". ```javascript import { capitalize } from '@brazilian-utils/brazilian-utils'; capitalize('jose da silva'); // Jose da Silva capitalize('JOSÉ DA SILVA'); // José da Silva capitalize('empresa ltda'); // Empresa LTDA capitalize('banco do brasil s.a.'); // Banco do Brasil S.A. capitalize('casa de carnes s/a'); // Casa de Carnes S/A ("S/A" is matched across the slash) capitalize('mogi-guaçu'); // Mogi-Guaçu ("-" starts a new word) capitalize("santa bárbara d'oeste"); // Santa Bárbara d'Oeste ("'" starts a new word, "d" stays lower case) capitalize("bob's"); // Bob's (a single letter after an apostrophe is the English possessive) capitalize('rua a, 100'); // Rua A, 100 (a preposition followed by punctuation is a designator) capitalize('fulano comércio me'); // Fulano Comércio ME ("ME" as the last word is the designation) capitalize('não-me-toque'); // Não-Me-Toque (anywhere else "me" is an ordinary word) capitalize('(empresa) ltda'); // (Empresa) LTDA capitalize('luiz von schmidt'); // Luiz von Schmidt capitalize('casa para todos'); // Casa para Todos (contracted prepositions such as "ao", "às", "pelo" and "sobre" stay lower case too) capitalize('empresa s.a'); // Empresa S.A capitalize('santana/rs'); // Santana/RS ("RS" is a state code right after a "/") capitalize('porto alegre/rs'); // Porto Alegre/RS capitalize('brasília - df'); // Brasília - DF (a state code as the last word after " - ", " – " or ", ") capitalize('santana rs'); // Santana Rs (no "/", so "rs" is just a word) capitalize('rua xv de novembro'); // Rua XV de Novembro (roman numeral, "de" stays lower case) capitalize('joão paulo ii'); // João Paulo II capitalize('rua xxiv de maio'); // Rua XXIV de Maio (roman numerals from II to XXXIX, except VI, the verb "vi") capitalize('de'); // De (a preposition keeps its capital when it is the first word) capitalize('empresa ltda', { upperCaseWords: [] }); // Empresa Ltda (the list given replaces the default one) capitalize('josé Ama MARIA', { lowerCaseWords: ['ama'] }); // José ama Maria capitalize('doc inválido', { upperCaseWords: ['DOC'] }); // DOC Inválido (case-insensitive match) capitalize(' josé maria '); // José Maria (every run of whitespace, tabs and newlines included, collapses into one space) ``` Source: [Manual de Redação da Presidência da República](https://www4.planalto.gov.br/centrodeestudos/assuntos/manual-de-redacao-da-presidencia-da-republica/manual-de-redacao.pdf). ### removeAccents Remove diacritical marks (accents, tildes, cedillas) from a string. - Every combining mark (Unicode general category M) is dropped, so accents from any script go. ```javascript import { removeAccents } from '@brazilian-utils/brazilian-utils'; removeAccents('São Paulo'); // 'Sao Paulo' removeAccents('Piauí'); // 'Piaui' removeAccents('Ceará'); // 'Ceara' removeAccents('Açaí'); // 'Acai' removeAccents(''); // '' ``` ## Inscrição estadual (IE) ### isValidIe Check if an inscrição estadual (state registration) is valid for a state. **Deprecated:** the positional form `isValidIe(stateCode, ie)` still works but is deprecated; use the object form `isValidIe({ value, stateCode })`. - Takes a single object (`IsValidIeParams`): `value` is the registration and `stateCode` the state it belongs to (a `StateCode`, case-insensitive, with surrounding whitespace ignored). - Some states have special cases, a prefix or format the SINTEGRA page does not print or a deliberate deviation from it (details and sources in the JSDoc in `src/is-valid-ie`): - GO: the prefixes 10, 11, 15 and 20 to 29, the union of sources that disagree: the norm (IN nº 946/09-GSF, art. 39, I, as worded by IN nº 1.535/22-GSE) gives 10, 20 and 11, the SINTEGRA page 10, 11 and 20 to 29, the 2012 roteiro de crítica 10, 11 and 15. The check digit follows the roteiro, as in 2.4.0: a remainder of 1 gives 1 in the range 10103105 to 10119997, and 11094402 takes either digit, special cases the SINTEGRA page (2022) does not have. - MT: 11 digits, or the 9 digits Portaria SEFAZ-MT nº 59/2025 (art. 8º, § 1º) prescribes, read as the 11 digit form padded with two zeros (no official text gives the check digit rule of the 9 digit form). - PA: the prefixes 15 and 75 to 79 the SINTEGRA page lists (SEFA-PA has issued 75 since 07/10/2024). MS: the prefixes 28 and 50 the SINTEGRA page gives (50 is also in a SEFAZ-MS e-CCE communiqué; the only norm, Resolução/SEF nº 1.344/1999, gives 28 alone). - DF: the 13 digit AC rule under the prefixes 07 and 08. The SINTEGRA page does not call 07 fixed; SEFAZ-DF's rule sheet calls it a "campo fixo". DF moved to 08 when the numbers starting with 07 ran out. - RR: the prefix 24, which the SINTEGRA page does not write as a rule: it is read from the page's ten examples. - SP: the produtor rural form `P0MMMSSSSD000`, the zero after the `P` included; the `P` may be written in lower case. - TO: the 9 digits in force (Portaria SEFAZ-TO nº 676/2002, art. 3º; RICMS-TO, Decreto nº 2.912/2006, art. 90), or the old 11 digits the SINTEGRA page documents, with the tipo digits 01, 02, 03 or 99. - AM: the page's check digit rule has two branches and leaves "Resto" undefined; the library reads it as the sum modulo 11 and gives 0 to a sum of 0 or 1, the shared modulus 11 rule. - MG: a first check digit of 10, from a sum that is already a multiple of ten, is read as 0. - PE: the 9 digit eFisco form and the old 14 digit CACEPE form, both on the SINTEGRA page (Portaria SF nº 087/2007 converted the old numbers but set no date after which they are void). - RO: the 14 digit form the SINTEGRA page gives for registrations since 01/08/2000. The 9 digit form it still prints for the earlier formula (`101.62521-3`) is rejected: those numbers were converted to 13 digits plus the check digit (`0000000062521-3`). - AL: the third digit, the tipo de empresa, must be 0, 3, 5, 7 or 8, the values the SINTEGRA page lists. - An all-zero registration is accepted wherever the published formula yields a check digit of 0 for it: AM, CE, ES, MG, PB, PE (9 digits), PI, PR, RJ, RS, SC, SE and SP, plus BA with 8 or 9 digits, MT with 9 or 11 digits and TO with 9 digits. ```javascript import { isValidIe } from '@brazilian-utils/brazilian-utils'; isValidIe({ value: '110042490114', stateCode: 'SP' }); // true isValidIe({ value: 'P011004243002', stateCode: 'SP' }); // true (produtor rural) isValidIe({ value: '0187634580933', stateCode: 'AC' }); // false isValidIe({ value: '109161793', stateCode: 'go' }); // true (case-insensitive) isValidIe({ value: '109161793', stateCode: ' GO ' }); // true (surrounding whitespace ignored) isValidIe({ value: '200000004', stateCode: 'GO' }); // true (prefix 20) isValidIe({ value: '130000019', stateCode: 'MT' }); // true (9 digits) ``` Source: [SINTEGRA state pages](http://www.sintegra.gov.br/insc_est.html), the [Goiás roteiro de crítica](https://goias.gov.br/economia/roteiro-de-critica-da-inscricao-estadual-de-goias/) and [IN nº 946/09-GSF](https://appasp.economia.go.gov.br/Legislacao/arquivos/secretario/in/IN_0946_2009.htm). ## Email ### isValidEmail Check if an email address is valid. A practical subset of the WHATWG HTML definition. - Local part: letters, digits and `_'+-.`, with no leading or trailing dot, no trailing apostrophe and no two dots in a row, and at most 64 characters. The whole address is capped at 254 characters (RFC 5321, section 4.5.3.1); up to 2.4.0 there was no cap on either. - Domain: at least one dot, labels of up to 63 characters, final label 2 to 63 letters or a punycode label (`xn--`, up to 63 characters, so `user@example.xn--p1ai` is valid). - Rejected, although WHATWG allows some of them: quoted local parts, address literals, single label domains such as `user@localhost`, and the local part characters `! # $ % & * = ? ^ { | } ~`, the slash and the backtick. ```javascript import { isValidEmail } from '@brazilian-utils/brazilian-utils'; isValidEmail('john.doe@hotmail.com'); // true isValidEmail('invalid.email'); // false isValidEmail('user@example.xn--p1ai'); // true (punycode top-level domain) isValidEmail('a%b@example.com'); // false (% is outside the accepted local part set) ``` Source: [WHATWG HTML, valid e-mail address](https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address) and [RFC 5322](https://www.rfc-editor.org/rfc/rfc5322). ## Credit card ### isValidCreditCard Check if a payment card number (credit or debit) is valid using the Luhn algorithm. Only the digit count (12 to 19) and the Luhn check digit are checked. There is no brand detection (Visa, Mastercard, Amex...), issuer range lookup or expiration/CVV checks. - Accepts a string or a number, with the mask characters (whitespace, `.`, `-` and `/`) anywhere between the digits. ```javascript import { isValidCreditCard } from '@brazilian-utils/brazilian-utils'; isValidCreditCard('4111111111111111'); // true (Visa test number) isValidCreditCard('5555555555554444'); // true (Mastercard test number) isValidCreditCard('378282246310005'); // true (American Express test number) isValidCreditCard('4111 1111 1111 1111'); // true (spaced mask) isValidCreditCard('4111 - 1111 - 1111 - 1111'); // true (a run of separators between the digits) isValidCreditCard('4111.1111/1111-1111'); // true (any of the mask characters) isValidCreditCard('4111111111111112'); // false (bad check digit) isValidCreditCard('0000000000000000'); // false (every digit the same, though the Luhn check passes) isValidCreditCard('4111a1111b1111c1111'); // false (letters between the digits) isValidCreditCard(4111111111111111111); // false (above 2^53 - 1, pass it as a string) ``` Source: [ISO/IEC 7812-1](https://www.iso.org/standard/70484.html). ## Professional registration ### isValidRegistroProfissional Check the structure of a professional council registration number (registro/inscrição profissional). Only the digit count and the UF are checked, never a check digit, even for CRC. - The separators of the mask (whitespace, `.`, `-` and `/`) are ignored wherever they sit; any other character (`@`, an emoji) makes the value invalid instead of being stripped. - Takes an object (`IsValidRegistroProfissionalParams`): `value`, `council` (`"OAB"`, `"CRM"`, `"CRO"`, `"CRP"` or `"CRC"`, a `RegistroProfissionalCouncil`) and an optional `stateCode` (expected UF, letter case and surrounding whitespace ignored). - `"OAB"` and `"CRM"`: 4 to 6 digits plus the UF (`123456/SP`, `123456-SP`); `"CRO"`: 3 to 6 digits (`12345/SP`), or the form of the Consolidação das Normas do CFO (Resolução CFO-63/2005), art. 115, § 1º: the sigla of the Conselho Regional first, joined by a hyphen to the category (`TPD`, `TSB`, `ASB`, `APD`, `CLM`/`CLF`, `LPM`/`LPF`, `PV`, `T`) when there is one, then the number, followed by `-IS` for a secundária or `-R` for a remida (`CRO-SP 12345`, `CRO-SP-TPD 1234`, `CRO-SP 12345-IS`). Up to 2.4.0 this form was rejected. - `"CRP"`: a 2-digit regional code (`01` to `24`) plus 4 to 6 digits (`06/12345`); `stateCode` is ignored. The CFP system has 24 regionals; the CRP-25 (Amapá) is only a proposal. - `"CRC"`: UF, 6 digits, tipo de registro (`O` or `P`) and check digit (`SP-123456/O-3`); a transfer appends `T` or `S` and the destination UF (`SP-123456/O-3 T-MG`). `stateCode` matches the originating UF. This shape and the `P`/`S` registrations come from the Manual de Registro of 2009; Resolução CFC nº 1.707/2023, in force, only sets a numbering "única e sequencial em cada CRC" and the `T` of the transfer, and the check digit algorithm is not published. - The digit counts of the OAB, CRM, CRO and CRP numbers are conventional: the OAB and the CFM publish no format, and neither the CFO's art. 115 nor the CFP fixes a digit count. CREA is not covered. ```javascript import { isValidRegistroProfissional } from '@brazilian-utils/brazilian-utils'; isValidRegistroProfissional({ value: '123456/SP', council: 'OAB' }); // true isValidRegistroProfissional({ value: '123456-RJ', council: 'OAB', stateCode: 'SP' }); // false (UF mismatch) isValidRegistroProfissional({ value: '123456', council: 'OAB' }); // false (no UF) isValidRegistroProfissional({ value: '12@3456/SP', council: 'OAB' }); // false (a character outside the mask) isValidRegistroProfissional({ value: 'CRO-SP-TPD 1234', council: 'CRO' }); // true (art. 115 of the CFO norms) isValidRegistroProfissional({ value: '06/12345', council: 'CRP' }); // true isValidRegistroProfissional({ value: 'SP-123456/O-3', council: 'CRC' }); // true isValidRegistroProfissional({ value: 'SP-123456/O-3 T-MG', council: 'CRC' }); // true (registro transferido) isValidRegistroProfissional({ value: 'SP-123456/T-3', council: 'CRC' }); // false ("T" is not a tipo de registro) ``` Source: [Consolidação das Normas do CFO, art. 115](https://transparencia.cfo.org.br/wp-content/uploads/2023/09/Consolida%C3%A7%C3%A3o-das-Normas-Atualizado-emsetembro-de-2023.pdf), [Manual de Registro do Sistema CFC/CRCs](https://cfc.org.br/wp-content/uploads/2018/04/1_manual_registro.pdf), [Resolução CFC nº 1.707/2023](https://www1.cfc.org.br/sisweb/SRE/docs/Res_1707.pdf), [CFP regional councils](https://site.cfp.org.br/cfp/sistema-conselhos/conselhos-pelo-brasil/). ## VIN ### isValidVin Check if a VIN (Vehicle Identification Number / chassi) is valid. By default it checks 17 characters in the three sections of Resolução CONTRAN nº 968/2022, art. 3º (the WMI, the VDS and the VIS), each a digit or a capital letter other than `I`, `O` and `Q`. - The `I`, `O` and `Q` exclusion comes from ISO 3779, not from the resolution: it lists no forbidden character and refers the engraving to ABNT NBR 6066:2022 (art. 5º), a paid standard with no official free copy. The regularization VINs of its Anexo II (WMI `XXX`) are written without those letters, so they pass. - **Options** (`IsValidVinOptions`): `checkDigit: true` also enforces the North-American rules of 49 CFR 565.15, the check digit at position 9 and a model year code other than `U`, `Z` or `0` at position 10. Use it for a VIN of a vehicle built for the United States or Canada. - Brazilian rules do not mandate the check digit, and many Brazilian-built VINs do not carry one. Up to 2.4.0 it was always enforced; pass `{ checkDigit: true }` to keep that behaviour. - Case-insensitive and trims surrounding whitespace; a value of one repeated character is rejected. A VIN is printed as one unbroken run, so a space, `.`, `-` or `/` among the characters is rejected instead of being stripped. Only the ASCII letters and digits count: a non-ASCII letter that upper cases into an ASCII one (`ſ`, `ß`) is rejected. ```javascript import { isValidVin } from '@brazilian-utils/brazilian-utils'; isValidVin('9BWZZZ377VT004251'); // true (Brazilian VIN, no check digit) isValidVin('9BWZZZ377VT004251', { checkDigit: true }); // false (its 9th character is not the check digit) isValidVin('1HGCM82633A004352', { checkDigit: true }); // true isValidVin('1m8gdm9axkp042788', { checkDigit: true }); // true (check digit X, lowercase) isValidVin('1HGCM82633A004353', { checkDigit: true }); // false (bad check digit) isValidVin('00000000000000000'); // false (every character the same) isValidVin('1HGCM8263IA004352'); // false (contains the excluded letter I) isValidVin('1HGCM82633A00435'); // false (16 characters) isValidVin('1HGCM 82633 A004352'); // false (a separator among the characters) ``` Source: [ISO 3779:2009](https://www.iso.org/standard/52200.html), [49 CFR 565.15](https://www.ecfr.gov/current/title-49/section-565.15) and [Resolução CONTRAN nº 968/2022](https://www.gov.br/transportes/pt-br/assuntos/transito/conteudo-contran/resolucoes/resolucao9682022.pdf). ## Standard Schema ### toStandardSchema Wrap an `isValid*` utility in a [Standard Schema](https://standardschema.dev), the validator format that form libraries, routers and API frameworks accept: TanStack Form, react-hook-form, tRPC, Hono and more. - The second argument (`ToStandardSchemaOptions`) takes `options`, handed to the validator on every call, and `message`, the message of the issue (default `'Invalid value'`). - It validates synchronously and does not transform: a valid value comes back as it was given, an invalid one yields a single issue, and a validator that throws counts as invalid. - Validators that take an object (`isValidBankAccount`, `isValidRegistroProfissional`, `isValidIe`) work the same way. Wrap the overloaded `isValidIe` in an arrow function: `toStandardSchema((params) => isValidIe(params))`. - The types of the specification (`StandardSchemaV1`, `StandardSchemaV1Result`, `StandardSchemaV1Issue` and the rest) are exported too, so nothing else is installed. ```javascript import { isValidCnpj, isValidCpf, toStandardSchema } from '@brazilian-utils/brazilian-utils'; const cpf = toStandardSchema(isValidCpf, { message: 'CPF inválido' }); cpf['~standard'].validate('123.456.789-09'); // { value: '123.456.789-09' } cpf['~standard'].validate('123'); // { issues: [{ message: 'CPF inválido' }] } const cnpj = toStandardSchema(isValidCnpj, { options: { version: 2 } }); // alphanumeric CNPJ // Anything that takes a Standard Schema takes it as is, a TanStack Form field for example ; ``` Inside a Zod or Valibot schema the validators plug in directly, with no wrapper, and the result is itself a Standard Schema: ```javascript import { standardSchemaResolver } from '@hookform/resolvers/standard-schema'; import { isValidCep, isValidCpf } from '@brazilian-utils/brazilian-utils'; import { useForm } from 'react-hook-form'; import * as v from 'valibot'; import { z } from 'zod'; const zodSchema = z.object({ cpf: z.string().refine(isValidCpf, 'CPF inválido'), cep: z.string().refine(isValidCep, 'CEP inválido'), }); const valibotSchema = v.object({ cpf: v.pipe(v.string(), v.check(isValidCpf, 'CPF inválido')), cep: v.pipe(v.string(), v.check(isValidCep, 'CEP inválido')), }); const form = useForm({ resolver: standardSchemaResolver(zodSchema) }); // or valibotSchema ``` Source: [Standard Schema specification](https://standardschema.dev).