Validador del Nuevo CNPJ Alfanumérico en JavaScript

Instrucción Normativa 2229/2024 de la Receita Federal de Brasil cambia el CNPJ a alfanumérico de 14 posiciones (8 raíz, 4 orden y 2 DV). Guía para adaptar validadores y bases de datos en integraciones fiscales

5 sept 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

La Receita Federal de Brasil publicó la Instrucción Normativa 2229 de 15 de octubre de 2024 que modifica la regla de formación del CNPJ en Brasil para ampliar la capacidad de generación de identificadores ante el agotamiento del modelo numérico tradicional.

El cambio impacta miles de sistemas y alcanza de forma directa a plataformas de facturación, emisión de documentos fiscales electrónicos y a los ambientes de autorización de las Administraciones Tributarias. Si trabajas con integración fiscal o contabilidad electrónica, es esencial adaptar validadores y bases de datos para aceptar la nueva estructura alfanumérica.

Referencias oficiales Nota Técnica DFe Conjunta CNPJ Alfanumérico v1.00 y su documento PDF.

Estructura del nuevo CNPJ

1 El CNPJ alfanumérico mantiene 14 posiciones

2 Las 8 primeras posiciones son la raíz y ahora son alfanuméricas

3 Las 4 posiciones siguientes son la orden y también son alfanuméricas

4 Las 2 últimas posiciones siguen siendo los dígitos verificadores numéricos

Cálculo del DV Dígito Verificador

Se utiliza módulo 11 y cada carácter se convierte a número según la regla valor = ASCII - 48

Ejemplos de conversión 0 ? 0 9 ? 9 A ? 17 B ? 18 Z ? 42

Implementación en JavaScript lista para producción

class CNPJ { static tamanhoCNPJSemDV = 12; static regexCNPJSemDV = /^([A-Z\d]){12}$/; static regexCNPJ = /^([A-Z\d]){12}(\d){2}$/; static regexCaracteresMascara = /[./-]/g; static cnpjZerado = `00000000000000`; static pesosDV = [6,5,4,3,2,9,8,7,6,5,4,3,2]; static isValid(cnpj) { let cnpjSemMascara = this.removeMascaraCNPJ(cnpj).toUpperCase(); if (this.regexCNPJ.test(cnpjSemMascara) && cnpjSemMascara !== this.cnpjZerado) { const dvInformado = cnpjSemMascara.substring(this.tamanhoCNPJSemDV); const dvCalculado = this.calculaDV(cnpjSemMascara.substring(0,this.tamanhoCNPJSemDV)); return dvInformado === dvCalculado; } return false; } static calculaDV(cnpj) { let cnpjSemMascara = this.removeMascaraCNPJ(cnpj).toUpperCase(); if (this.regexCNPJSemDV.test(cnpjSemMascara) && cnpjSemMascara !== this.cnpjZerado.substring(0,this.tamanhoCNPJSemDV)) { let somatorioDV1=0; let somatorioDV2=0; for (let i=0; i < this.tamanhoCNPJSemDV; i++) { const asciiDigito = cnpjSemMascara.charCodeAt(i)-48; somatorioDV1 += asciiDigito * this.pesosDV[i+1]; somatorioDV2 += asciiDigito * this.pesosDV[i]; } const dv1 = somatorioDV1 % 11 < 2 ? 0 : 11 - (somatorioDV1 % 11); somatorioDV2 += dv1 * this.pesosDV[this.tamanhoCNPJSemDV]; const dv2 = somatorioDV2 % 11 < 2 ? 0 : 11 - (somatorioDV2 % 11); return `${dv1}${dv2}`; } throw new Error(`No es posible calcular el DV porque el CNPJ proporcionado es inválido`); } static removeMascaraCNPJ(cnpj) { return cnpj.replace(this.regexCaracteresMascara, ``); } }

Ejemplo de uso

const raiz = `A1B2C3D4E5F6`; const dv = CNPJ.calculaDV(raiz); console.log(`DV calculado: ${dv}`); const cnpjCompleto = raiz + dv; console.log(`CNPJ completo: ${cnpjCompleto}`); console.log(`Es válido? ${CNPJ.isValid(cnpjCompleto)}`);

Salida esperada de ejemplo

DV calculado: 12

CNPJ completo: A1B2C3D4E5F612

Es válido? true

Sobre Q2BSTUDIO

En Q2BSTUDIO desarrollamos aplicaciones a medida y software a medida preparados para cambios normativos como el nuevo CNPJ alfanumérico, integrando validaciones, pruebas automatizadas y despliegues seguros. Si tu organización necesita modernizar su ecosistema con microservicios, APIs y frontends escalables, descubre nuestros servicios de desarrollo de aplicaciones y software multiplataforma.

También impulsamos la transformación digital con inteligencia artificial e IA para empresas, diseño de agentes IA, servicios cloud AWS y Azure, ciberseguridad y pentesting, automatización de procesos, servicios inteligencia de negocio y analítica avanzada con power bi. Conectamos datos, procesos y modelos para crear productos robustos y seguros. Conoce cómo aplicamos modelos generativos, RAG y MLOps a tus casos de uso con inteligencia artificial.

Si necesitas asesoramiento para adaptar tus validadores, normalizar bases de datos, actualizar reglas de negocio o desplegar pipelines CI CD con pruebas de conformidad fiscal, nuestro equipo puede ayudarte a planificar y ejecutar la migración minimizando riesgos y asegurando continuidad operativa.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat