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

@lacussoft/cpf-val

v3.0.0

Published

Utility to validate CPF (Brazilian Individual's Taxpayer ID)

Downloads

163

Readme

cpf-val para JavaScript

🌎 Access documentation in English

Utilitário em JavaScript/TypeScript para validar CPFs (Cadastro de Pessoas Físicas).

Recursos

  • Entrada flexível: Aceita string ou array de strings (formatado ou bruto)
  • Agnóstico ao formato: Remove caracteres não numéricos antes da validação
  • TypeScript: Definições de tipo completas e compatível com strict mode
  • Dependências mínimas: Sem dependências externas, apenas pacotes internos como @lacussoft/utils, e @lacussoft/cpf-dv para o cálculo dos dígitos verificadores
  • Tratamento de erros: Erro de tipo específico para tipo de entrada inválido

Instalação

# com NPM
$ npm install --save @lacussoft/cpf-val

# com Bun
$ bun add @lacussoft/cpf-val

Início rápido

// ES Modules
import cpfVal from '@lacussoft/cpf-val'

// Common JS
const cpfVal = require('@lacussoft/cpf-val')

Uso básico:

cpfVal('12345678909')      // true
cpfVal('123.456.789-09')   // true
cpfVal('12345678910')      // false (dígitos verificadores inválidos)

cpfVal(['123', '456', '789', '09'])  // true (array de strings)

Para frontends legados, inclua o build UMD (ex.: minificado) em uma tag <script>; cpfVal fica disponível globalmente:

<script src="https://cdn.jsdelivr.net/npm/@lacussoft/cpf-val@latest/dist/cpf-val.min.js"></script>

Uso

cpfVal (função auxiliar)

Valida uma string ou array de strings de CPF. Retorna true se a entrada for um CPF válido (11 dígitos após sanitização, base elegível e dígitos verificadores corretos), caso contrário false. Entrada inválida (ex.: tamanho errado, base ineligível como dígitos repetidos) resulta em false sem lançar exceção. É um atalho para new CpfValidator().isValid(cpfInput).

  • cpfInput: CpfInput — string ou array de strings (formatado ou bruto; caracteres não numéricos são removidos).

Lança: CpfValidatorInputTypeError se a entrada não for string nem string[].

CpfValidator (classe)

Para lógica de validação reutilizável, use a classe:

import { CpfValidator } from '@lacussoft/cpf-val'

const validator = new CpfValidator()

validator.isValid('123.456.789-09')   // true
validator.isValid('12345678909')      // true
validator.isValid(['123', '456', '789', '10'])  // false
  • constructor: new CpfValidator() — sem opções.
  • isValid(cpfInput): Retorna true se o CPF for válido, false caso contrário.

Formatos de entrada

Entrada em string: dígitos simples ou CPF formatado (ex.: 123.456.789-09). Caracteres não numéricos são removidos automaticamente. Deve ter 11 dígitos após a sanitização.

Array de strings: strings de um ou vários caracteres (concatenadas antes da validação), ex.: ['1','2','3','4','5','6','7','8','9','0','9'], ['123','456','789','09'].

API

Exportações

  • cpfVal (padrão): (cpfInput: CpfInput) => boolean
  • CpfValidator: Classe para validar CPF (sem opções).
  • CPF_LENGTH: 11 (constante).
  • Tipos: CpfInput (string | readonly string[]).

Erros e exceções

Este pacote usa TypeError para tipo de entrada inválido. Valores de CPF inválidos (tamanho errado, base ineligível) retornam false e não lançam exceção.

  • CpfValidatorTypeError (abstract) — base para erros de tipo
  • CpfValidatorInputTypeError — entrada não é string nem string[]
  • CpfValidatorException (abstract) — base para exceções não relacionadas a tipo (atualmente não utilizada por este pacote)
import cpfVal, {
  CpfValidatorInputTypeError,
  CpfValidatorTypeError,
} from '@lacussoft/cpf-val'

// Tipo de entrada (ex.: número não permitido)
try {
  cpfVal(12345678909)
} catch (e) {
  if (e instanceof CpfValidatorInputTypeError) {
    console.log(e.message)  // CPF input must be of type string or string[]. Got integer number.
  }
}

// Qualquer erro de tipo do pacote
try {
  cpfVal(null)
} catch (e) {
  if (e instanceof CpfValidatorTypeError) {
    // tratar
  }
}

Contribuição e suporte

Contribuições são bem-vindas! Consulte as Diretrizes de contribuição. Se o projeto for útil para você, considere:

Licença

Este projeto está sob a licença MIT — veja o arquivo LICENSE.

Changelog

Veja o CHANGELOG para alterações e histórico de versões.


Feito com ❤️ por Lacus Solutions