 CPF (Cadastro de Pessoas Físicas) is a Brazilian tax identification number for individuals.

To validate a CPF (Cadastro de Pessoas Físicas) in Brazil, you can follow these steps:

1. Remove any non-digit characters from the CPF, such as dots or hyphens.
2. Check if the resulting string has 11 digits.
3. If the resulting string has 11 digits, check if it is not composed of the same digit repeated 11 times.
4. Calculate the first verification digit (digit 10) of the CPF by multiplying each of the first 9 digits of the CPF by a weight ranging from 10 to 2, summing the results, and then applying the modulus 11. If the result is less than 2, the first verification digit is 0, otherwise it is 11 minus the result.
5. Calculate the second verification digit (digit 11) of the CPF using a similar process, but with a weight ranging from 11 to 2.
6. Check if the calculated verification digits match the last two digits of the CPF.

Exemplo de Javascript code:

``````function validateCPF(cpf) {
cpf = cpf.replace(/[^\d]+/g,'');
if (cpf.length !== 11 || /^(\d)\1{10}\$/.test(cpf)) {
return false;
}
var sum = 0;
for (var i = 0; i < 9; i++) {
sum += parseInt(cpf.charAt(i)) * (10 - i);
}
var rest = sum % 11;
var digit1 = (rest < 2) ? 0 : (11 - rest);
sum = 0;
for (var i = 0; i < 10; i++) {
sum += parseInt(cpf.charAt(i)) * (11 - i);
}
rest = sum % 11;
var digit2 = (rest < 2) ? 0 : (11 - rest);
return (digit1 === parseInt(cpf.charAt(9)) && digit2 === parseInt(cpf.charAt(10)));
}
``````

Categories:

Tags:

## Comentários

Nenhum comentário para mostrar.