Validate CPF using WPF

Asked

Viewed 641 times

-3

How can I check if a CPF number is valid using WPF in C#?

You need to create some class?

  • 1

    What have you tried? It gets very vague the question like this.

  • Related: http://answall.com/q/11470/101

1 answer

3

How can I check if a CPF number is valid using WPF in C#? [...]

First of all, whether or not you use WPF makes no difference. The language is C# and that’s what matters. To know if a CPF is valid, there is an algorithm that can be easily found on the internet.

Note that the algorithm can only verify if a CPF is valid according to the rules established by the country and not whether it is an active CPF or not.

[...] You need to create some class?

It depends on your organization, whatever. I have a class Valida which I use to do some validations on one of my projects.

Below the code I use to validate CPF’s, the algorithm has been removed from here. It may require some modifications, but that’s the basis, and it’s completely functional that way.

Note that the algorithm asks for an integer as parameter, if you save the CPF with dots and dash, you need to remove them and convert to integer before trying to validate (or adapt the function to receive in the format you save).

using static System.Convert;

public static class Valida
{
    public static bool Cpf(int cpf)
    {
        string strCpf = cpf.ToString().PadLeft(11, '0');

        if (strCpf.All(x => x == strCpf[0]))
            return false;

        var listCpf = strCpf.Select(num => ToInt32(num.ToString())).ToList();

        if (listCpf[9] != Mod11Cpf(listCpf, 10))
            return false;

        if (listCpf[10] != Mod11Cpf(listCpf, 11))
            return false;

        return true;
    }

    internal static int Mod11Cpf(List<int> elementos, int @base)
    {
        int soma = 0;
        for (int i = 0; i < (@base - 1); i++)
            soma += (@base - i) * elementos[i];

        int dv1, resto = soma % 11;

        if (resto < 2)
            dv1 = 0;
        else
            dv1 = 11 - resto;

        return dv1;
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.