Discussion

Pegasystems Inc.
BR
Last activity: 27 May 2025 16:16 EDT
How to Validate CPF in a Form Using Custom Function
Introduction
The CPF (Cadastro de Pessoas Físicas) is the Brazilian individual taxpayer identification number, consisting of 11 digits.
Proper validation of CPF numbers is crucial for any application that collects Brazilian user data, as it ensures data integrity and compliance with Brazilian regulations.
Step-by-step guide
Demonstrates how to implement CPF validation in your Pega application using a custom function, allowing you to verify the mathematical validity of CPF numbers before processing them.
Step 1: Create a Library
Why create a library? Creating a dedicated library helps organize your code, promotes reusability across your application, and makes maintenance easier by centralizing your validation logic in one location.
In this example, I create a new library named 'ValidateHowTo'. Add the 'Java.io.' and 'Java.util.' packages to use their methods, which provide essential functionality for string manipulation and data processing.
Step 2: Create a Function to Return the Correct Digits of the CPF
Why create a custom function? A custom function allows you to implement the specific mathematical algorithm required for CPF validation, which verifies that the last two digits (verification digits) match the expected values calculated from the first nine digits.
NOTE: At the end of the article, there is an update in this function to return a boolean value.
Create a function in the library you just created and select it for use.
2.1 - In the Input Parameters
Add the following parameter:
- Name: CPF - Java type: String
2.2 - Add the Following Java Code in the 'Java' Tab
''' if (CPF == null || CPF.equals("")) { return ""; } else { int[] cpfDigits = new int[11]; String cpf = CPF.replaceAll("\\D", ""); for (int i = 0; i < 9; i++) { cpfDigits[i] = Character.getNumericValue(cpf.charAt(i)); } // Calcula primeiro dígito int soma1 = 0; for (int i = 0; i < 9; i++) { soma1 += cpfDigits[i] * (10 - i); } int digito1 = (soma1 * 10) % 11; cpfDigits[9] = (digito1 == 10 || digito1 == 11) ? 0 : digito1; // Calcula segundo dígito int soma2 = 0; for (int i = 0; i < 10; i++) { soma2 += cpfDigits[i] * (11 - i); } int digito2 = (soma2 * 10) % 11; cpfDigits[10] = (digito2 == 10 || digito2 == 11) ? 0 : digito2; // Retorna o CPF completo StringBuilder cpfCompleto = new StringBuilder(); for (int i = 0; i < 11; i++) { cpfCompleto.append(cpfDigits[i]); } return digito1+""+digito2; } '''
2.3 - Press the Buttons Above the Code in the Order They Are Presented
The buttons perform operations like syntax checking, compilation, and saving in a specific sequence that ensures your code is properly validated and integrated into the system.
Step 3: Create a Data Transform to Validate the Information
Note: Use the function you just created by clicking on the gear icon and searching in the Expression builder.
Step 4: Add the Field You Are Going to Validate in the View
The view is where users will input the CPF number, so adding a dedicated field ensures proper data collection and provides a clear interface element for users to enter their information.
Step 5: Go to Pre/Post Processing Tab and Select the Data Transform
Select the Data Transform you created in the select option for the Post processing.
Note: Post processing allows you to automatically validate the CPF immediately after the user enters it, providing real-time feedback without requiring additional user actions like clicking a validation button.
Step 6: Validate Your Work
Why test your implementation? Testing ensures that your CPF validation works correctly for both valid and invalid CPF numbers, confirming that your implementation meets the requirements and provides the expected user experience.
Conclusion
By following these steps, you have successfully implemented CPF validation in your Pega application. This validation ensures that only mathematically valid CPF numbers are accepted, improving data quality and user experience. The implementation uses a reusable function that can be called from multiple places in your application, making your code more maintainable and consistent.
Remember that while this validation checks the mathematical validity of a CPF number, it doesn't verify if the number is actually registered with the Brazilian Federal Revenue. For complete validation in production systems, consider implementing additional checks or integrating with official validation services when necessary.
This approach to CPF validation demonstrates how to leverage Pega's capabilities to implement country-specific validation rules efficiently, a pattern you can apply to other types of document validation as well.
After my post, I made some changes to the function.
1 – I created a new function based on the first one, but this time it is called IsValidCPF and returns a Boolean value.
2 – I added the Java code below:
''' if (CPF == null || CPF.trim().isEmpty()) { // Use trim() and isEmpty() for better handling of whitespace return false; } String cpfCleaned = CPF.replaceAll("\\D", ""); // Remove all non-digits // Check if the cleaned CPF has 11 digits if (cpfCleaned.length() != 11) { return false; } // Check for common patterns of invalid CPFs (all digits are the same) // This is a common shortcut for invalid CPFs, but not strictly part of the algorithm itself. if (cpfCleaned.matches("(\\d)\\1{10}")) { return false; } int[] cpfDigits = new int[11]; for (int i = 0; i < 11; i++) { cpfDigits[i] = Character.getNumericValue(cpfCleaned.charAt(i)); } // Calculate first verification digit int soma1 = 0; for (int i = 0; i < 9; i++) { soma1 += cpfDigits[i] * (10 - i); } int digito1Calculated = (soma1 * 10) % 11; if (digito1Calculated == 10 || digito1Calculated == 11) { digito1Calculated = 0; } // Calculate second verification digit int soma2 = 0; for (int i = 0; i < 10; i++) { soma2 += cpfDigits[i] * (11 - i); } int digito2Calculated = (soma2 * 10) % 11; if (digito2Calculated == 10 || digito2Calculated == 11) { digito2Calculated = 0; } // Compare calculated digits with the actual last two digits of the input CPF return (digito1Calculated == cpfDigits[9] && digito2Calculated == cpfDigits[10]); '''
3 – After testing and generating, the function can be found in the Expression builder.
4 – To use it, just call it in the data transform in a when action.
5 – Here is the test of the new function:
NOTE: Remember this is just an improvement of the previous function that returned the digits.