Validate, generate and format CPF/CNPJ numbers. Include command-line tools.
Switch branches/tags
Latest commit f383414 Oct 26, 2017 @fnando fnando Bump up version.
Failed to load latest commit information.
bin Change code style. Oct 26, 2017
lib Bump up version. Oct 26, 2017
test Use correct namespace. Oct 26, 2017
.gitignore Remove Gemfile.lock. Mar 7, 2016
.rubocop.yml Fix ruby-2.3. Oct 26, 2017
.travis.yml Fix ruby-2.3. Oct 26, 2017
Gemfile Change code style. Oct 26, 2017
LICENSE Initial commit. Aug 15, 2012 Add support for strict validation. Nov 1, 2016
Rakefile Change code style. Oct 26, 2017
cpf_cnpj.gemspec Change code style. Oct 26, 2017


Build Status Code Climate Gem Version

This gem does some CPF/CNPJ magic. It allows you to create, validate and format CPF/CNPJ, even through the command-line.

Just making my life easier when filling these damn numbers on internet bankings and government sites.

For ActiveModel/ActiveRecord validations, please check


Add this line to your application's Gemfile:

gem "cpf_cnpj"

And then execute:

$ bundle

Or install it yourself as:

$ gem install cpf_cnpj


Ruby API

This library has the same API for both CNPJ/CPF, so only one of them is documented below.

require "cpf_cnpj"

CPF.valid?(number)    # Check if a CPF is valid
CPF.generate          # Generate a random CPF number
CPF.generate(true)    # Generate a formatted number

cpf =
cpf.formatted         # Return formatted CPF (
cpf.stripped          # Return stripped CPF (xxxxxxxxxxx)
cpf.valid?            # Check if CPF is valid

Strict Validation

By default, validations will strip any characters that aren't numbers. This means that 532#####820------857\n96 is considered a valid number. To perform a strict validation use strict: true.

CPF.valid?(number, strict: true)


This library gives you two binaries: cpf and cnpj.

$ cpf --check 532.820.857-96
$ $?

$ cpf --check 53282085796
$ $?

$ cpf --format 53282085796

$ cpf --strip 532.820.857-96

$ cpf --generate

$ cpf --generate --strip

$ echo 76001454809 | cpf -f


  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am "Added some feature")
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request