Functions for formatting and validating CNPJ values.
This module supports both the numeric CNPJ model and the alphanumeric model announced by Receita Federal for new registrations from July 2026.
Summary
Types
A formatted CNPJ follows the XX.XXX.XXX/XXXX-XX mask.
A normalized CNPJ has 14 characters and no punctuation.
Functions
Calculates the two numeric check digits for a 12-character CNPJ base.
Formats a CNPJ using the XX.XXX.XXX/XXXX-XX mask.
Formats a CNPJ, raising ArgumentError when the input is invalid.
Removes punctuation and normalizes a CNPJ to uppercase.
Removes punctuation and normalizes a CNPJ, raising on invalid input.
Returns true when the CNPJ format and check digits are valid.
Returns true when the CNPJ has a supported shape.
Types
Functions
Calculates the two numeric check digits for a 12-character CNPJ base.
Examples
iex> BrDocs.CNPJ.check_digits("000000000001")
"91"
iex> BrDocs.CNPJ.check_digits("AB12CD340001")
"84"
Formats a CNPJ using the XX.XXX.XXX/XXXX-XX mask.
The input may be numeric or alphanumeric, with or without punctuation. The last two characters must be numeric because they are check digits.
Examples
iex> BrDocs.CNPJ.format("00000000000191")
{:ok, "00.000.000/0001-91"}
iex> BrDocs.CNPJ.format("ab12cd34000184")
{:ok, "AB.12C.D34/0001-84"}
iex> BrDocs.CNPJ.format("123")
{:error, :invalid_format}
Formats a CNPJ, raising ArgumentError when the input is invalid.
Examples
iex> BrDocs.CNPJ.format!("00000000000191")
"00.000.000/0001-91"
@spec unformat(String.t()) :: {:ok, normalized()} | {:error, :invalid_format}
Removes punctuation and normalizes a CNPJ to uppercase.
Examples
iex> BrDocs.CNPJ.unformat("00.000.000/0001-91")
{:ok, "00000000000191"}
iex> BrDocs.CNPJ.unformat("ab.12c.d34/0001-84")
{:ok, "AB12CD34000184"}
@spec unformat!(String.t()) :: normalized()
Removes punctuation and normalizes a CNPJ, raising on invalid input.
Examples
iex> BrDocs.CNPJ.unformat!("00.000.000/0001-91")
"00000000000191"
Returns true when the CNPJ format and check digits are valid.
Examples
iex> BrDocs.CNPJ.valid?("00.000.000/0001-91")
true
iex> BrDocs.CNPJ.valid?("AB.12C.D34/0001-84")
true
iex> BrDocs.CNPJ.valid?("AB.12C.D34/0001-00")
false
Returns true when the CNPJ has a supported shape.
This checks length and allowed characters, but does not calculate check
digits. Use valid?/1 for full validation.
Examples
iex> BrDocs.CNPJ.valid_format?("00.000.000/0001-91")
true
iex> BrDocs.CNPJ.valid_format?("AB12CD34000109")
true
iex> BrDocs.CNPJ.valid_format?("AB12CD340001AA")
false