Validate CPF using WPF [closed]

-3

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

Do I need to create some class?

    
asked by anonymous 03.10.2016 / 18:16

1 answer

3
  

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

First, using or not WPF makes no difference at all. Language is C # and that's what matters. To find out if a CPF is valid, there is an algorithm that can be easily found on the internet.

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

  

[...] Do you need to create some class?

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

Below the code I use to validate CPF's, the algorithm has been removed from here . Some modifications may be necessary, but the basis is this and it is fully functional in this way.

See that the algorithm asks for an integer as a parameter, if you save the dotted and dashed CPF, you must remove them and convert to integer before attempting to validate (or adapt the function to receive in the format you saved).

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;
    }
}
    
03.10.2016 / 18:22