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

@gfinnovation/br-validations

v2.0.1

Published

Brazilian CPF and CNPJ validation utilities

Downloads

2,461

Readme

@gfinnovation/br-validations

TypeScript utilities for validating, formatting, cleaning, and transforming Brazilian CPF and CNPJ documents.

The package supports:

  • Individual and Unified CPF/CNPJ validation
  • Individual and Unified CPF/CNPJ formatting
  • Individual and Unified CPF/CNPJ cleaning
  • Alphanumeric CNPJ validation
  • class-validator decorator for CPF/CNPJ validation
  • class-transformer decorator for automatic CPF/CNPJ normalization
  • TypeScript support
  • ESM and CommonJS builds

Installation

npm install @gfinnovation/br-validations

If you use decorators with class-validator or class-transformer, also install:

npm install class-validator class-transformer reflect-metadata

NestJS Integration (v11.0.0)

If you are using this package inside a NestJS (v11.0.0) project, ensure you have the core common utilities installed:

# npm
npm i @nestjs/common@^11.0.0

# yarn
yarn add @nestjs/common@^11.0.0

# pnpm
pnpm add @nestjs/common@^11.0.0

And import metadata once in your application entrypoint:

import 'reflect-metadata';

Features

| Feature | Supported | |---|---| | Validate CPF | ✅ | | Validate CNPJ | ✅ | | Validate Alphanumeric CNPJ | ✅ | | Unified Validate (CPF/CNPJ) | ✅ | | Format CPF | ✅ | | Format CNPJ | ✅ | | Unified Format (CPF/CNPJ) | ✅ | | Clean CPF | ✅ | | Clean CNPJ | ✅ | | Unified Clean (CPF/CNPJ) | ✅ | | NestJS v11.0.0 compatible | ✅ | | class-validator decorator | ✅ | | class-transformer decorator | ✅ | | TypeScript support | ✅ |


Importing

import {
  // CPF Utilities
  validateCPF,
  formatCPF,
  cleanCPF,
  
  // CNPJ Utilities
  validateCNPJ,
  formatCNPJ,
  cleanCNPJ,
  
  // Unified Utilities (CPF or CNPJ)
  cpfCnpjValidate,
  cpfCnpjFormat,
  cpfCnpjClean,
  
  // Decorators
  IsCpfCnpjValid,
  CpfCnpjTransform,
} from '@gfinnovation/br-validations';

Unified Utilities (CPF / CNPJ)

These functions dynamically detect whether the input is a CPF or CNPJ and apply the corresponding logic.

cpfCnpjValidate

Validates either a CPF or a CNPJ (including alphanumeric CNPJ).

import { cpfCnpjValidate } from '@gfinnovation/br-validations';

cpfCnpjValidate('589.831.040-15'); // true (CPF)
cpfCnpjValidate('12.345.678/0001-95'); // true (CNPJ)
cpfCnpjValidate('invalid-value'); // false

cpfCnpjFormat

Formats a raw string into a standard CPF or CNPJ mask based on length.

import { cpfCnpjFormat } from '@gfinnovation/br-validations';

cpfCnpjFormat('12345678900'); // 123.456.789-00
cpfCnpjFormat('12345678000195'); // 12.345.678/0001-95

cpfCnpjClean

Removes punctuation and symbols from both CPF and CNPJ formatted strings.

import { cpfCnpjClean } from '@gfinnovation/br-validations';

cpfCnpjClean('123.456.789-00'); // 12345678900
cpfCnpjClean('12.345.678/0001-95'); // 12345678000195

CPF Specific Utilities

validateCPF

import { validateCPF } from '@gfinnovation/br-validations';

validateCPF('589.831.040-15'); // true
validateCPF('123.456.789-00'); // false

formatCPF

import { formatCPF } from '@gfinnovation/br-validations';

formatCPF('12345678900'); // 123.456.789-00

cleanCPF

import { cleanCPF } from '@gfinnovation/br-validations';

cleanCPF('123.456.789-00'); // 12345678900

CNPJ Specific Utilities

validateCNPJ

Supports numeric, alphanumeric, and formatted variants.

import { validateCNPJ } from '@gfinnovation/br-validations';

validateCNPJ('12.345.678/0001-95'); // true
validateCNPJ('11.ANE.A76/0001-75'); // true

formatCNPJ

import { formatCNPJ } from '@gfinnovation/br-validations';

formatCNPJ('12345678000195'); // 12.345.678/0001-95
formatCNPJ('11ANEA76000175'); // 11.ANE.A76/0001-75

cleanCNPJ

import { cleanCNPJ } from '@gfinnovation/br-validations';

cleanCNPJ('11.ANE.A76/0001-75'); // 11ANEA76000175

class-validator Decorator

IsCpfCnpjValid

Decorator for validating CPF or CNPJ fields inside DTOs.

import { IsCpfCnpjValid } from '@gfinnovation/br-validations';

class CreateUserDto {
  @IsCpfCnpjValid()
  document: string;
}

class-transformer Decorator

CpfCnpjTransform

Automatically pads and transforms CPF or CNPJ values during data instantiation.

import 'reflect-metadata';
import { CpfCnpjTransform } from '@gfinnovation/br-validations';

class PaymentDto {
  tpPessoaPagdr: string;

  @CpfCnpjTransform()
  documento: string;
}

NestJS Example

Combines @nestjs/common decorators with @gfinnovation/br-validations for data transfer objects (DTOs) and automatic payload validation/transformation:

import { Controller, Post, Body, UsePipes, ValidationPipe } from '@nestjs/common';
import { IsCpfCnpjValid, CpfCnpjTransform } from '@gfinnovation/br-validations';

export class CreateUserDto {
  tpPessoaPagdr: string;

  @CpfCnpjTransform()
  @IsCpfCnpjValid()
  documento: string;
}

@Controller('users')
export class UsersController {
  @Post()
  @UsePipes(new ValidationPipe({ transform: true }))
  create(@Body() createUserDto: CreateUserDto) {
    return {
      message: 'User validated and formatted successfully',
      data: createUserDto,
    };
  }
}

NestJS Pipe Example

This package does not provide a NestJS pipe implementation.

If you need to normalize and validate route parameters, create a custom pipe using the validation functions exported by this package.

import {
  ArgumentMetadata,
  BadRequestException,
  Injectable,
  PipeTransform,
} from '@nestjs/common';

import {
  validateCPF,
  validateCNPJ,
  cpfCnpjClean,
} from '@gfinnovation/br-validations';

@Injectable()
export class CpfCnpjPipeTransform implements PipeTransform {
  transform(
    value: string | number | null | undefined,
    metadata: ArgumentMetadata,
  ): string {
    if (value == null) {
      throw new BadRequestException('CPF/CNPJ is required');
    }

    value = cpfCnpjClean(String(value).trim().toUpperCase());

    const isNumeric = /^\d+$/.test(value);

    const normalized = isNumeric
      ? value.length <= 11
        ? value.padStart(11, '0')
        : value.padStart(14, '0')
      : value;

    if (normalized.length === 11 && !validateCPF(normalized)) {
      throw new BadRequestException('Invalid CPF');
    }

    if (normalized.length === 14 && !validateCNPJ(normalized)) {
      throw new BadRequestException('Invalid CNPJ');
    }

    return normalized;
  }
}

Usage:

@Get(':document')
findByDocument(
  @Param('document', CpfCnpjPipeTransform)
  document: string,
) {
  return document;
}

Build

npm run build

Test

npm test

TypeScript Configuration

If you use decorators, enable the following in your tsconfig.json:

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  }
}

Troubleshooting & pnpm Support

Because pnpm handles nested node_modules strictly using hard links, it will not automatically resolve optional peer dependencies required by `decorators unless they are explicitly installed in the root project.

Missing Peer Dependencies Error

If you use @IsCpfCnpjValid or @CpfCnpjTransform and experience runtime errors or type failures using pnpm, verify you have installed the required validation peer dependencies:

pnpm add class-validator class-transformer reflect-metadata

Decorator Metadata Issues

If NestJS fails to inject or read your DTO types during request validation, ensure your .npmrc or project configurations do not strictly isolate the metadata context, and that reflect-metadata is imported at the very top of your application entry point (main.ts):

import 'reflect-metadata'; // Must be the first line
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

License

ISC