CNPJ
CNPJ identifier validation and formatting for Crystal already compatible with the new alphanumeric CNPJ what will be available in 2026.
CNPJ (Cadastro Nacional de Pessoa JurÃdica) is a Brazilian nationwide registry of legal entities. It's an 14-character sequence in the format XX.XXX.XXX/XXXX-00, where the last 2 digits are check digits, generated through an arithmetic operation on the first 12 digits.
Installation
-
Add the dependency to your
shard.yml
:dependencies: cnpj: github: stephannv/cnpj
-
Run
shards install
Usage
require "cnpj"
# With valid formatted value
cnpj = CNPJ.new("24.485.147/0001-87")
cnpj.value # => "24.485.147/0001-87"
cnpj.formatted # => "24.485.147/0001-87"
cnpj.unformatted # => "24485147000187"
# With valid unformatted value
cnpj = CNPJ.new("24485147000187")
cnpj.value # => "24485147000187"
cnpj.formatted # => "24.485.147/0001-87"
cnpj.unformatted # => "24485147000187"
A CNPJ
object is designed to never hold an invalid value, so you can assume
that a CNPJ object will always hold a valid value. If you try to initialize a
CNPJ object with an invalid value, it will raise an exception:
CNPJ.new("11111111111111") # => raises `ArgumentError`
CNPJ.new("11.111.111/1111-11") # => raises `ArgumentError`
To safely initialize a CNPJ object, use the .parse
method:
# With invalid value
CNPJ.parse("11111111111111") # => nil
# With valid value
CNPJ.parse("24.485.147/0001-87") # => #<CNPJ:0x104fe0ae0 @value="24.485.147/0001-87">
You can use CNPJ::Validator
module to validate a CNPJ identifier:
CNPJ::Validator.valid?("11111111111111") # => false
CNPJ::Validator.valid?("24.485.147/0001-87") # => true
Development
shards install
to install dependenciescrystal spec
to run tests
Contributing
- Fork it (https://github.com/stephannv/cnpj/fork)
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request
Contributors
- stephann - creator and maintainer