Learn To Check If A CPF Is Valid

The Brazilian legal document for people can be validated with math.

The mask for input is 999.999.999-99.

The last two digits are based on a formula.

There are no duplicate CPFs in Brazil. Every legal person in Brazil has his own, and he needs to open a bank account and get public services.

Here is a function that I use in my projects,

public static bool ValidarCPF(string cpf)
{
    try
    {
        var multiplicador1 = new[] { 10, 9, 8, 7, 6, 5, 4, 3, 2 };
        var multiplicador2 = new[] { 11, 10, 9, 8, 7, 6, 5, 4, 3, 2 };
        cpf = cpf.Trim();
        cpf = cpf.Replace(".", string.Empty).Replace("-", string.Empty);
        if (cpf.Length != 11)
            return false;
        var tempCpf = cpf[..9];
        var soma = 0;
        for (var i = 0; i < 9; i++)
            soma += int.Parse(tempCpf[i].ToString()) * multiplicador1[i];
        var resto = soma % 11;
        resto = resto < 2 ? 0 : 11 - resto;
        var digito = resto.ToString();
        tempCpf += digito;
        soma = 0;
        for (var i = 0; i < 10; i++)
            soma += int.Parse(tempCpf[i].ToString()) * multiplicador2[i];
        resto = soma % 11;
        resto = resto < 2 ? 0 : 11 - resto;
        digito += resto;
        return cpf.EndsWith(digito);
    }
    catch
    {
        return false;
    }
}

Call the function from a string. It should have only numbers and eleven digits.

if (ValidarCPF("11111111112")) {
    return "CPF is ok!";
} else {
    return "CPF is invalid!";
}

If you are working in or for Brazil, this can be useful.


Similar Articles