Discussion

Pegasystems Inc.
BR
Last activity: 26 May 2025 16:38 EDT
How to Validate CNPJ in a Form Using Function
Introduction
The CNPJ (Cadastro Nacional da Pessoa Jurídica) is Brazil's official 14-digit corporate tax identification number, essential for business operations and regulatory compliance. In Pega applications serving Brazilian markets, implementing robust CNPJ validation ensures data integrity and prevents processing errors that could impact business workflows.
This step-by-step guide demonstrates how to create a comprehensive CNPJ validation function within the Pega platform, leveraging the same library structure used for CPF validation to maintain consistency across your application's validation framework.
Step-by-step guide
Step 1: Create a Library (or use an existing one)
In this example, we are using an existing library named 'ValidateHowTo' (previously created for CPF validation article).
WHY reuse an existing library? Consolidating validation functions in a single library promotes code reusability, simplifies maintenance, and ensures consistent validation behavior across your application. This approach also reduces development time and minimizes the risk of inconsistencies between different validation implementations.
- How to Validate CPF in a Form Using Custom Function
Step 2: Create a function named 'IsValidCNPJ'
Create a function named 'IsValidCNPJ' to return 'true' or 'false' based on the CNPJ provided, and select the library you just created.
WHY use a boolean return type? A simple true/false response provides clear, unambiguous validation results that can be easily integrated into conditional logic, data transforms, and user interface validation feedback mechanisms.
Step 2.1: Configure Input Parameters
In the Input parameters, add
- Name: CNPJ - Java type: String
Although CNPJ contains only digits, using String type accommodates formatted input (with dots, slashes, and hyphens) and prevents issues with leading zeros that could be lost with numeric types.
Step 2.2: Add the Java validation code
Add the following Java code in the 'Java' tab:
''' // 1. Verifica se o CNPJ é nulo ou vazio/apenas espaços em branco if (CNPJ == null || CNPJ.trim().isEmpty()) { return false; } // 2. Remove caracteres não numéricos String cnpjCleaned = CNPJ.replaceAll("\\D", ""); // 3. Verifica se o CNPJ tem 14 Digitos após a limpeza if (cnpjCleaned.length() != 14) { return false; } // 4. Verifica CNPJs com todos os Digitos iguais (geralmente inválidos) // Ex: "00000000000000", "11111111111111", etc. if (cnpjCleaned.matches("(\\d)\\1{13}")) { return false; } // 5. Converte o CNPJ limpo para um array de inteiros int[] cnpjDigits = new int[14]; for (int i = 0; i < 14; i++) { cnpjDigits[i] = Character.getNumericValue(cnpjCleaned.charAt(i)); } // --- Cálculo do Primeiro Digito Verificador (DV1) --- int soma1 = 0; int peso = 5; // Peso inicial para o primeiro Digito for (int i = 0; i < 12; i++) { soma1 += cnpjDigits[i] * peso; peso--; if (peso == 1) { // Quando o peso chega a 1, ele volta para 9 peso = 9; } } int dv1Calculated = 11 - (soma1 % 11); if (dv1Calculated >= 10) { // Se o resto for 0 ou 1, o DV é 0 dv1Calculated = 0; } // 6. Compara o DV1 calculado com o 13 Digito do CNPJ original if (dv1Calculated != cnpjDigits[12]) { return false; } // --- Cálculo do Segundo Digito Verificador (DV2) --- int soma2 = 0; peso = 6; // Peso inicial para o segundo Digito (agora incluindo o DV1) for (int i = 0; i < 13; i++) { soma2 += cnpjDigits[i] * peso; peso--; if (peso == 1) { // Quando o peso chega a 1, ele volta para 9 peso = 9; } } int dv2Calculated = 11 - (soma2 % 11); if (dv2Calculated >= 10) { // Se o resto for 0 ou 1, o DV é 0 dv2Calculated = 0; } // 7. Compara o DV2 calculado com o 14 Digito do CNPJ original if (dv2Calculated != cnpjDigits[13]) { return false; } // 8. Se todas as verificações passarem, o CNPJ é válido return true; '''
Step 2.3: Process the code
Press the buttons above the code in the order they are presented to compile and validate the function. Pega's development environment requires specific compilation steps to properly validate syntax, resolve dependencies, and integrate the function into the platform's runtime environment.
Step 3: Create a Data Transform to validate the information
Create a Data Transform to validate the information using the function you just created by clicking the gear icon and searching in the Expression builder.
Step 4: Add the field you are going to validate in the view
Add the CNPJ field that requires validation to your user interface view.
Step 5: Configure Post Processing
Navigate to the Pre/Post Processing tab and select the Data Transform in the Post processing option.
Step 6: Validate the implementation
Test the validation function with various CNPJ inputs to ensure proper functionality.
Conclusion
This implementation provides a comprehensive CNPJ validation solution that integrates seamlessly with Pega's validation framework. By following Brazilian regulatory standards and implementing the validation at the platform level, you ensure consistent data quality across all application touchpoints. The reusable library approach promotes maintainability and allows for easy extension to other Brazilian document validation requirements.
The validation function handles common input variations, implements the official check digit algorithm, and provides clear boolean responses suitable for integration with Pega's conditional logic and user feedback mechanisms. This approach ensures that your application maintains high data quality standards while providing a smooth user experience for Brazilian business processes.
References
1. https://taxid.pro/docs/countries/brazil
2. https://docs.pega.com/bundle/platform-241/page/platform/app-dev/validat…