Results:

No results found

Logo

Home Articles Alphanumeric CNPJ

Updated technical guide for 2026

Alphanumeric CNPJ: The Complete Guide for Developers and Businesses

Understand the new format, the July 2026 rollout timeline, and everything that must change in forms, databases, APIs, validation rules, input masks, and Laravel projects.

Published on June 6, 2026 Technical and practical reading
Alphanumeric CNPJ connected to source code, APIs, validation, and databases

Quick Summary

Starting in July 2026, the Brazilian Federal Revenue Service is expected to begin the gradual assignment of alphanumeric CNPJs to newly registered businesses. Existing CNPJs will not be changed. The identifier will still contain 14 characters, but the first 12 positions may combine letters and numbers, while the final two check digits will remain numeric. For technology teams, the impact is straightforward: a CNPJ can no longer be treated as a numeric-only value.

Introduction: A Small Change to the Identifier, a Major Change for Systems

For decades, Brazilian developers have treated the CNPJ as a sequence of 14 digits. Forms rely on numeric keyboards, databases store it in integer or decimal columns, APIs strip out anything that is not a number, and regular expressions look for exactly 14 digits. These decisions made sense under the traditional format, but they are no longer compatible with the alphanumeric CNPJ.

The change announced by the Brazilian Federal Revenue Service does not replace the current format. In practice, both standards will coexist: organizations already registered will keep their numeric CNPJs, while new registrations may receive identifiers containing letters and numbers. This makes the migration more complex, because it is not enough to replace one rule with another. Systems must support both formats without changing historical data, removing leading zeros, or rejecting valid letters.

This guide was written for development, architecture, data, QA, product, tax, and operations teams. Its purpose is to translate the official rules into practical decisions: how to store CNPJs, normalize input, calculate check digits, update regex patterns and masks, review API contracts, and organize testing before the new model takes effect.

What Is the Alphanumeric CNPJ?

The alphanumeric CNPJ is the evolution of the identifier used to recognize companies and other entities before the Brazilian public administration. It remains a 14-character code and preserves the familiar visual format with dots, slash, and hyphen. The difference lies in the set of characters allowed in the first 12 positions.

The first eight positions form the CNPJ root. The following four represent the establishment order, such as headquarters or branch offices. Under the new format, both groups may contain letters from A to Z and digits from 0 to 9. The final two positions remain reserved for check digits and must stay numeric. A simplified structural representation is SS.SSS.SSS/SSSS-NN, where S accepts letters or numbers and N accepts numbers only.

One example published for testing purposes is 12.ABC.345/01DE-35. It demonstrates that letters may appear in both the root and establishment-order sections, while the suffix 35 remains numeric. The traditional example 12.345.678/0001-95 also remains valid. This coexistence is the most important concept of the entire migration.

Why Did the Federal Revenue Service Create the New Format?

The primary reason is to expand the number of available combinations. The continuous growth in the number of companies, entities, headquarters, and branch offices puts pressure on the numbering capacity offered by the purely numeric model. By introducing letters into the 12 identification positions, the number of possible codes increases dramatically without changing the total length of the identifier.

Keeping the 14-character length reduces visual impact and avoids a much larger disruption across documents, user interfaces, and integrations. However, having the same length does not mean automatic compatibility: any implementation that equates “14 characters” with “14 digits” must be reviewed.

According to the Federal Revenue Service, the goal is to ensure the continuity of registrations and maintain the availability of new identifiers. The change was formalized through Normative Instruction RFB No. 2,229, dated October 15, 2024, which updated the CNPJ rules. For the latest updates, visit the official alphanumeric CNPJ page.

July 2026 Implementation Timeline

The official rollout is expected to begin in July 2026. The assignment of alphanumeric CNPJs will apply to new registrations and will be introduced gradually. Therefore, July 2026 should not be interpreted as the date when all Brazilian CNPJs will be converted or when existing companies will automatically receive a new identifier.

Current CNPJs will remain valid. This means payment platforms, ERPs, CRMs, tax systems, document issuers, supplier registries, banks, insurance companies, marketplaces, and government agencies will need to process both traditional and alphanumeric identifiers simultaneously. The period before implementation should be used for inventory, development, testing, and partner communication.

Before July

Map dependencies, adapt data models, review suppliers, and create automated tests.

Starting July 2026

Expected beginning of the gradual rollout for new registrations.

During the Coexistence Period

Accept and validate both formats across all channels and integrations.

Differences Between Traditional and Alphanumeric CNPJ

Feature Traditional Alphanumeric
Number of Characters 14 14
Root (positions 1–8) Numbers only Letters and numbers
Establishment Order (positions 9–12) Numbers only Letters and numbers
Check Digits Two numbers Two numbers
Visual Format 00.000.000/0000-00 SS.SSS.SSS/SSSS-00
Recommended Storage Text Text

Even under the traditional format, storing a CNPJ as text was already the safest option because it may begin with zero and is never used in arithmetic operations. With the introduction of letters, this recommendation becomes a functional requirement. A CNPJ is not a numeric value; it is a textual identifier.

Impacts on Systems, Databases, and Integrations

The biggest risk is usually not the function that calculates the check digits, but the dozens of places that transform, transport, or store a CNPJ. An application may validate it correctly in a form and still lose letters in a queue, CSV file, stored procedure, legacy integration, or any service that performs sanitization such as replace(/\D/g, '').

Database

INT, BIGINT, DECIMAL, and similar column types should be migrated to a text-based type capable of storing at least 14 unformatted characters. Review unique indexes, foreign keys, audit tables, replicas, data warehouses, and materialized views. The application should enforce a canonical format—preferably uppercase and without punctuation—to avoid logical duplicates.

APIs and Contracts

In JSON, a CNPJ must be represented as a string. OpenAPI, GraphQL, Protobuf schemas, and gateway validation rules should reflect this. Documentation that describes the field as an integer or provides only numeric examples must be updated. It is also important to review digital signatures, hash generation, idempotency keys, and routing rules that include the CNPJ.

Imports, Exports, and Analytics

Spreadsheets may automatically convert values to numbers; fixed-width files may accept 14 characters but reject letters; data pipelines may cast the column to a numeric type; reports may sort or group values incorrectly. Test CSV, Excel, EDI, XML, tax documents, webhooks, queues, logs, and BI tools. The migration is only complete when the value can travel through the entire workflow without being altered.

User Interfaces and Accessibility

Fields using type="number" or inputmode="numeric" prevent or discourage letter input. Prefer type="text", appropriate length limits, and visual conversion to uppercase. Messages such as “enter the 14 digits” should be updated to “enter the 14 CNPJ characters.”

Alphanumeric CNPJ Validation Example in JavaScript

The calculation still relies on the modulo 11 algorithm. For each character in the first 12 positions, use the decimal value of its ASCII code minus 48. This means 0 equals 0, 9 equals 9, and A equals 17. The weights for the first and second check digits are then applied.

function normalizeCnpj(value) {
  return value
    .toUpperCase()
    .replace(/[.\-\/\s]/g, '');
}

function calculateDigit(base) {
  const weights = base.length === 12
    ? [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
    : [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];

  const sum = [...base].reduce((total, char, index) => {
    const value = char.charCodeAt(0) - 48;
    return total + value * weights[index];
  }, 0);

  const remainder = sum % 11;
  return remainder < 2 ? 0 : 11 - remainder;
}

function isValidCnpj(value) {
  const cnpj = normalizeCnpj(value);

  if (!/^[A-Z0-9]{12}[0-9]{2}$/.test(cnpj)) {
    return false;
  }

  if (/^([A-Z0-9])\1{11}[0-9]{2}$/.test(cnpj)) {
    return false;
  }

  const firstDigit = calculateDigit(cnpj.slice(0, 12));
  const secondDigit = calculateDigit(cnpj.slice(0, 12) + firstDigit);

  return cnpj.endsWith(`${firstDigit}${secondDigit}`);
}

console.log(isValidCnpj('12.ABC.345/01DE-35')); // true
console.log(isValidCnpj('12.345.678/0001-95')); // true

The regex only validates the structure. It does not replace check-digit verification. In production, keep normalization, structural validation, and mathematical validation as separate, explicit steps covered by unit tests.

PHP Validation Example

In PHP, ord() returns the character code. The example below accepts formatted or unformatted input, converts letters to uppercase, and compares the two calculated check digits against the identifier suffix.

<?php

function normalizeCnpj(string $value): string
{
    return strtoupper(preg_replace('/[.\-\/\s]/', '', $value));
}

function calculateCnpjDigit(string $base): int
{
    $weights = strlen($base) === 12
        ? [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
        : [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];

    $sum = 0;

    foreach (str_split($base) as $index => $char) {
        $value = ord($char) - 48;
        $sum += $value * $weights[$index];
    }

    $remainder = $sum % 11;

    return $remainder < 2 ? 0 : 11 - $remainder;
}

function isValidCnpj(string $value): bool
{
    $cnpj = normalizeCnpj($value);

    if (! preg_match('/^[A-Z0-9]{12}[0-9]{2}$/', $cnpj)) {
        return false;
    }

    $base = substr($cnpj, 0, 12);
    $firstDigit = calculateCnpjDigit($base);
    $secondDigit = calculateCnpjDigit($base.$firstDigit);

    return substr($cnpj, -2) === $firstDigit.$secondDigit;
}

In a shared library, avoid duplicating this algorithm across controllers, jobs, and import routines. Create a single service or value object responsible for normalization, formatting, type detection, and validation. Centralizing this logic reduces inconsistencies when rules or test cases evolve.

Laravel Adaptation Examples

In Laravel, a dedicated validation rule keeps Form Requests clean and allows reuse across web endpoints, APIs, and import commands. The rule should accept a string, normalize the value, and delegate the check-digit calculation to a testable implementation.

<?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;

final class Cnpj implements ValidationRule
{
    public function validate(
        string $attribute,
        mixed $value,
        Closure $fail
    ): void {
        if (! is_string($value) || ! isValidCnpj($value)) {
            $fail('O campo :attribute deve conter um CNPJ válido.');
        }
    }
}

$validated = $request->validate([
    'cnpj' => ['required', 'string', 'max:18', new Cnpj()],
]);

$validated['cnpj'] = normalizeCnpj($validated['cnpj']);

Normalization should occur before persistence. One option is to use a model mutator, but this behavior must be documented so that queries, factories, and integrations remain consistent. If your application uses DTOs or actions, perform normalization at the domain boundary.

Database migrations should replace numeric column types with strings while preserving indexes. In large databases, plan for locking, parallel column creation, backfilling, validation, and gradual cutovers instead of a blocking schema change.

Schema::table('companies', function (Blueprint $table) {
    $table->string('cnpj', 14)->change();
});

Schema::create('companies', function (Blueprint $table) {
    $table->id();
    $table->string('cnpj', 14)->unique();
    $table->string('name');
    $table->timestamps();
});

Laravel tests should cover at least: a valid traditional CNPJ, a valid alphanumeric CNPJ, formatted input, lowercase letters normalized to uppercase, invalid characters, incorrect length, invalid check digits, and persistence without punctuation. Integration tests should verify the JSON payload sent to external services, not just the value stored locally.

Regex and Input Mask Updates

A common legacy regex is ^\d{14}$. While it correctly rejects unexpected characters under the current model, it also rejects every new alphanumeric identifier. For normalized values, the basic structure becomes ^[A-Z0-9]{12}[0-9]{2}$.

Do not use [A-z], as that range includes additional ASCII characters beyond letters. Also, do not allow letters in the final two check-digit positions. If your application accepts lowercase input, convert it to uppercase before applying regex validation. When removing punctuation, strip only expected separators; overly aggressive sanitization can hide invalid input.

Input masks based on symbols that mean “required digit” must be updated to support alphanumeric characters. If your masking library does not support this, a simple progressive formatter may be more predictable:

function formatCnpj(value) {
  const cnpj = value
    .toUpperCase()
    .replace(/[^A-Z0-9]/g, '')
    .slice(0, 14);

  return cnpj
    .replace(/^(.{2})(.{0,3})/, '$1.$2')
    .replace(/^(.{2})\.(.{3})(.{0,3})/, '$1.$2.$3')
    .replace(/^(.{2})\.(.{3})\.(.{3})(.{0,4})/, '$1.$2.$3/$4')
    .replace(/^(.{2})\.(.{3})\.(.{3})\/(.{4})(.{0,2})/, '$1.$2.$3/$4-$5')
    .replace(/[.\-\/]$/, '');
}

Input masks improve readability but should never be the source of truth. The backend must still validate the value. Users can disable JavaScript, call APIs directly, or upload files that bypass form validation.

How to Test Forms and Integrations

A solid strategy combines unit, integration, and end-to-end testing. Unit tests should verify normalization and check-digit calculations. HTTP tests should submit both formats to your endpoints. Browser tests should confirm that keyboards, masks, copy-and-paste behavior, error messages, and screen readers work correctly. Integration tests should use staging environments and verify the value received by downstream systems.

To generate test data, use the Utinix CNPJ Generator, which supports the alphanumeric format by default while still offering the traditional format. To verify structure and check digits, use the CNPJ Validator. These tools are intended for technical testing purposes only; generated values do not represent real companies and have no legal registration validity.

Migration Checklist for Developers and Businesses

Use the list below as a starting point for your compliance and migration plan. In larger organizations, assign an owner, deadline, test evidence, and priority level to each item.

Inventory all fields, screens, APIs, files, and reports that use CNPJ values.
Replace numeric columns with text-based columns capable of storing at least 14 characters.
Preserve leading zeros and standardize uppercase letters.
Replace sanitization routines that remove everything except digits.
Update regex patterns to support 12 alphanumeric characters followed by 2 digits.
Adapt input masks without allowing letters in the final two positions.
Review Form Requests, DTOs, serializers, and domain rules.
Update OpenAPI specifications, GraphQL schemas, events, queues, and webhooks.
Validate integrations with ERPs, banks, payment gateways, and third-party providers.
Review CSV, Excel, XML, and fixed-width file import/export processes.
Create automated tests covering both traditional and alphanumeric formats.
Monitor parsing errors and rejected records after deployment.
Train support, tax, registration, sales, and operations teams.
Keep official registration lookups separate from mathematical validation.

Migration Mistakes to Avoid

The first mistake is updating only the frontend. A screen may accept letters while the backend continues stripping non-numeric characters. The second is migrating the database but forgetting satellite systems and external partners. The third is allowing letters in any position, including the final check digits. The fourth is assuming that a mathematically valid CNPJ proves that a company actually exists.

Another risk is maintaining two separate implementations of the validation algorithm: one for traditional CNPJs and another for alphanumeric ones. Since the new rules remain compatible with numeric-only inputs, a single implementation can validate both formats. This reduces duplicated code and simplifies testing. Also, avoid modifying CNPJs already stored in your systems: normalizing punctuation is not the same as generating or replacing a company’s official identifier.

Finally, do not wait until the first alphanumeric CNPJ reaches production. This migration affects vendors, contracts, and historical data, which means it requires time for testing and validation. A well-executed inventory often reveals unexpected dependencies, including file names, directory structures, caches, metrics, URLs, permissions, and fraud-prevention rules.

FAQ: Frequently Asked Questions About the Alphanumeric CNPJ

When will the alphanumeric CNPJ start being used?

The rollout is expected to begin in July 2026 and will be implemented gradually for new CNPJ registrations. Existing CNPJs will remain valid and will not be automatically converted.

Will existing companies need to change their CNPJ?

No. The Brazilian Federal Revenue Service has stated that previously assigned CNPJs will remain valid. However, systems and integrations must support both the traditional numeric format and the new alphanumeric format simultaneously.

How many characters will an alphanumeric CNPJ have?

It will still contain 14 characters. The first eight positions (the root) and the next four positions (the establishment order) may contain letters and numbers. The final two positions remain numeric check digits.

Has the check-digit calculation changed?

The modulo 11 algorithm and weighting factors remain the same. The main adjustment is converting letters and numbers into numeric values based on their ASCII code minus 48 before applying the calculation.

Can I store a CNPJ in a numeric database column?

No. A CNPJ should be stored as text, such as VARCHAR(14), because it may contain letters and because leading zeros are part of the identifier. Numeric columns may also introduce unwanted conversions or precision issues.

Will legacy CNPJ regex patterns continue to work?

Regex patterns that only accept 14 digits will no longer recognize new alphanumeric CNPJs. Structural validation must accept 12 alphanumeric characters followed by two numeric check digits, in addition to validating the check-digit calculation itself.

Are uppercase and lowercase letters treated differently?

Input should be normalized to uppercase before storage and validation. This prevents inconsistencies across forms, APIs, queries, and unique indexes.

Does validating the check digits confirm that a company exists?

No. Mathematical validation only confirms that the structure and check digits are consistent. Company existence and registration status must be verified through official Federal Revenue Service sources.

Can masks such as 00.000.000/0000-00 still be used?

The familiar visual format with dots, slash, and hyphen can be preserved, but each position in the root and establishment-order sections must accept either a letter or a number. Libraries configured for numeric-only input will need to be updated or replaced.

How can I test the migration before July 2026?

Create automated test cases using both traditional and alphanumeric CNPJs, review databases and API contracts, and use the Utinix CNPJ Generator and Validator to test forms, imports, and integrations without relying on real company data.

Conclusion

The alphanumeric CNPJ preserves the 14-character structure and the two numeric check digits, but it changes a fundamental assumption deeply embedded in Brazilian software systems: the identifier is no longer exclusively numeric. Existing companies do not need to replace their current CNPJs, but their systems must be prepared to accept new identifiers containing letters once the rollout begins in July 2026.

The safest migration approach starts with a complete inventory, followed by the definition of a canonical text-based format, centralized normalization and validation, contract reviews, and end-to-end testing across the entire workflow. The sooner technical and business teams treat this as a data and integration migration project, the lower the risk of rejected registrations, truncated records, and silent failures.

This technical content is based on information published by the Brazilian Federal Revenue Service. Operational rules and implementation timelines may change; always verify regulatory decisions using official sources.

Share with your friends:

Comments: 0