DEV Community

Mehru
Mehru

Posted on

How the Brazilian CPF Validation Algorithm Works in JavaScript (Step-by-Step)

If you're building software for Brazilian users, you've probably come across the CPF (Cadastro de Pessoas Físicas). It's Brazil's individual taxpayer identification number and is commonly required in registration forms, financial systems, and government services.

For developers, validating a CPF correctly is essential to prevent invalid data from entering an application. In this article, I'll explain how the validation algorithm works and how you can implement it in JavaScript.
What Is a CPF?

A CPF consists of 11 digits.

Example:

529.982.247-25

The structure is:

First 9 digits: Base number
Last 2 digits: Verification digits (check digits)

These final two digits are calculated mathematically from the previous digits, helping detect typing mistakes and invalid numbers.
Step 1: Remove Formatting

Before validation, remove dots and hyphens.

Example:

529.982.247-25

becomes

52998224725
Step 2: Basic Validation

First verify:

Length is exactly 11 digits.
Contains only numeric characters.
Reject repeated sequences like:
00000000000
11111111111
22222222222

These are not considered valid CPFs.

Step 3: Calculate the First Check Digit

Multiply the first nine digits by the weights:

10 9 8 7 6 5 4 3 2

Add the results together.

Calculate:

sum % 11

If the remainder is less than 2:

checkDigit = 0

Otherwise:

checkDigit = 11 - remainder
Step 4: Calculate the Second Check Digit

Repeat the process using the first ten digits.

Weights become:

`11 10 9 8 7 6 5 4 3 2

Apply the same calculation.

The resulting digit must match the last digit of the CPF.

JavaScript Example:

`function isValidCPF(cpf) {
cpf = cpf.replace(/\D/g, '');

if (cpf.length !== 11) return false;
if (/^(\d)\1+$/.test(cpf)) return false;

let sum = 0;

for (let i = 0; i < 9; i++) {
sum += parseInt(cpf[i]) * (10 - i);
}

let remainder = sum % 11;
let digit1 = remainder < 2 ? 0 : 11 - remainder;

if (digit1 !== parseInt(cpf[9])) return false;

sum = 0;

for (let i = 0; i < 10; i++) {
sum += parseInt(cpf[i]) * (11 - i);
}

remainder = sum % 11;
let digit2 = remainder < 2 ? 0 : 11 - remainder;

return digit2 === parseInt(cpf[10]);
}`

Open Source Project

To better understand the algorithm, I created a lightweight open-source JavaScript implementation that developers can explore, modify, and improve.

GitHub Repository:

👉 https://github.com/Mehruunisa/cpf-validator-js/

As Iam a Beginner Contributions, suggestions, and feedback are always welcome.

Top comments (0)