npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@dmalbuquerque/cpf-cnpj-validator

v1.0.3

Published

Biblioteca para gerar, validar e formatar CPF, CNPJ e CNPJ alfanumérico com suporte para integração com Joi.

Readme

License Version

Documentação da Biblioteca de CPF e CNPJ

O objetivo do projeto é facilitar a validação e geração de CPF, CNPJ e CNPJ alfanumérico. Também é possível validar CPF e CNPJ utilizando a biblioteca Joi.

Instalação

npm install @dmalbuquerque/cpf-cnpj-validator

Como importar a biblioteca

Para projetos com Typescript

import { cpf, cnpj, documentValidator} from '@dmalbuquerque/cpf-cnpj-validator';

console.log(cpf.isValid('21156032300'));
console.log(cnpj.isValid('20245526000149'));

Para projetos com Javascript

const { cpf, cnpj, documentValidator} = require('@dmalbuquerque/cpf-cnpj-validator');

console.log(cpf.isValid('21156032300'));
console.log(cnpj.isValid('20245526000149'));

ou

const documents = require('@dmalbuquerque/cpf-cnpj-validator');

console.log(documents.cpf.isValid('21156032300'));
console.log(documents.cnpj.isValid('20245526000149'));

Como usar

CPF

Gerar um CPF

  • CPF numérico sem formatação:
    cpf.generate(); // Exemplo de retorno: "07208766053"
  • CPF formatado:
    cpf.generate({ formatted: true }); // Exemplo de retorno: "072.087.660-53"

Validar um CPF

  • CPF válido:
    cpf.isValid("07208766053"); // Retorna: true
    cpf.isValid("072.087.660-53"); // Retorna: true
  • CPF inválido:
    cpf.isValid("07208766050"); // Retorna: false
    cpf.isValid("072.087.660-50"); // Retorna: false

Formatar um CPF

  • Converter um CPF numérico para o formato padrão:
    cpf.format("07208766053"); // Retorna: "072.087.660-53"

CNPJ

Gerar um CNPJ

  • CNPJ clássico sem formatação:

    cnpj.generate({ type: "numeric" }); // Exemplo de retorno: "25143815000150"

    ou

    cnpj.generate();
  • CNPJ clássico formatado:

    cnpj.generate({ type: "numeric", formatted: true }); // Exemplo de retorno: "25.143.815/0001-50"
  • CNPJ alfanumérico sem formatação:

    cnpj.generate({ type: "alfanumeric" }); // Exemplo de retorno: "OGZP0N77444Y42"
  • CNPJ alfanumérico formatado:

    cnpj.generate({ type: "alfanumeric", formatted: true }); // Exemplo de retorno: "OG.ZP0.N77/444Y-42"

Validar um CNPJ

  • CNPJ clássico válido:
    cnpj.isValid("25143815000150"); // Retorna: true
    cnpj.isValid("25.143.815/0001-50"); // Retorna: true
  • CNPJ clássico inválido:
    cnpj.isValid("25143815000140"); // Retorna: false
    cnpj.isValid("25.143.815/0001-40"); // Retorna: false
  • CNPJ alfanumérico válido:
    cnpj.isValid("OGZP0N77444Y42"); // Retorna: true
    cnpj.isValid("OG.ZP0.N77/444Y-42"); // Retorna: true
  • CNPJ alfanumérico inválido:
    cnpj.isValid("OGZP0N77444Y40"); // Retorna: false
    cnpj.isValid("OG.ZP0.N77/444Y-40"); // Retorna: false

Formatar um CNPJ

  • Converter um CNPJ numérico para o formato padrão:
    cnpj.format("25143815000150"); // Retorna: "25.143.815/0001-50"
  • Converter um CNPJ alfanumérico para o formato padrão:
    cnpj.format("OGZP0N77444Y42"); // Retorna: "OG.ZP0.N77/444Y-42"

Validação com Joi

Esta biblioteca também permite a validação de CPF e CNPJ utilizando a biblioteca Joi. Veja um exemplo de implementação:

import Joi from "joi";
import documentValidator from "@dmalbuquerque/cpf-cnpj-validator";

const joi = Joi.extend(documentValidator);

const schema = Joi.object({
  cpf: joi.document().cpf().optional().label("CPF"),
  cnpj: joi.document().cnpj().required().label("CNPJ"),
});

const resultado = schema.validate({ cpf: null, cnpj: "25143815000150" });
console.log(resultado.error ? resultado.error.details : "Dados válidos!");

🔹 Regras de Validação

| Cenário | CPF | CNPJ | Resultado | |----------|-----|------|-----------| | Valor null | ✅ Aceito | ✅ Aceito | ✅ Válido | | String vazia ("") | ❌ CPF não pode ser vazio | ❌ CNPJ não pode ser vazio | ❌ Erro | | Campo obrigatório ausente | ❌ CPF é obrigatório | ❌ CNPJ é obrigatório | ❌ Erro |

Testes Automatizados

Esta biblioteca possui testes automatizados para garantir a qualidade do código. Para rodá-los localmente, basta executar o seguinte comando:

npm run test

Isso irá rodar todos os testes definidos usando o Jest. Certifique-se de ter o Jest instalado em seu ambiente de desenvolvimento.

Como Contribuir

Se você deseja contribuir para este projeto, siga as etapas abaixo:

  1. Faça um fork deste repositório.
  2. Clone o repositório forkado para o seu ambiente local.
  3. Instale as dependências do projeto: npm install.
  4. Faça suas alterações e testes.
  5. Execute os testes localmente para garantir que tudo esteja funcionando corretamente: npm run test
  6. Crie uma nova branch para suas alterações: git checkout -b minha-feature.
  7. Abra o PR com suas alterações.

✔️ Licença

Destribuido sob a licença MIT. © Daniel Albuquerque