cpf v1.0.0
[!WARNING] This repository is no longer maintained. Development will continue in the gunbolt/cpf_cnpj project, which provides the same features with expanded support for both CPF and CNPJ identifiers, along with database and serialization integrations.
CPF
CPF identifier validation and formatting for Crystal.
CPF (Cadastro de Pessoa Física) is the Brazilian individual taxpayer registry. It's an 11-digit identifier in the format 000.000.000-00, where the last 2 digits are check digits, generated through an arithmetic operation on the first nine digits.
Links
Installation
-
Add the dependency to your
shard.yml:dependencies: cpf: github: stephannv/cpf -
Run
shards install
Usage
require "cpf"
# With valid formatted value
cpf = CPF.new("640.061.830-97")
cpf.value # => "640.061.830-97"
cpf.formatted # => "640.061.830-97"
cpf.unformatted # => "64006183097"
cpf.to_s # => "640.061.830-97"
# With valid unformatted value
cpf = CPF.new("64006183097")
cpf.value # => "64006183097"
cpf.formatted # => "640.061.830-97"
cpf.unformatted # => "64006183097"
cpf.to_s # => "64006183097"
A CPF object is designed to never hold an invalid value, so you can assume that a CPF object will always hold a valid value. If you try to initialize a CPF object with an invalid value, it will raise an exception:
CPF.new("11111111111") # => raises `ArgumentError`
CPF.new("111.111.111-11") # => raises `ArgumentError`
To safely initialize a CPF object, use the .parse method:
# With invalid value
CPF.parse("11111111111") # => nil
# With valid value
CPF.parse("640.061.830-97") # => #<CPF:0x104fe0ae0 @value="640.061.830-97">
You can use CPF::Validator module to validate a CPF identifier:
CPF::Validator.valid?("11111111111") # => false
CPF::Validator.valid?("640.061.830-97") # => true
Development
shards installto install dependenciescrystal specto run tests
Contributing
- Fork it (https://github.com/stephannv/cpf/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
cpf
- 1
- 0
- 0
- 0
- 1
- 23 days ago
- January 28, 2025
MIT License
Sun, 19 Oct 2025 18:10:42 GMT