Find out what type a CNPJ verifier is

Asked

Viewed 1,503 times

1

I have a class where I can find out if the CNPJ entered by the user is valid or not.

What I’d like to do, and what I’m not getting, is show the user which are the last two valid digits he should type.

For example:

MessageBox("CNPJ inválido, o Digito Verificador correto seria: "+DV);

I would like to do this for the CNPJ and CPF.

The CNPJ validation method is the following::

public bool ValidaCNPJ(string vrCNPJ)
    {
        int nrDig;
        string CNPJ = vrCNPJ.Replace(".", "");
        CNPJ = CNPJ.Replace("/", "");
        CNPJ = CNPJ.Replace("-", "");

        string ftmt = "6543298765432";
        int[] digitos = new int[14];
        int[] soma = new int[2];
        soma[0] = 0;
        soma[1] = 0;
        int[] resultado = new int[2];
        resultado[0] = 0;
        resultado[1] = 0;
        bool[] CNPJOk = new bool[2];
        CNPJOk[0] = false;
        CNPJOk[1] = false;

        try
        {
            for (nrDig = 0; nrDig < 14; nrDig++)
            {
                digitos[nrDig] = int.Parse(
                 CNPJ.Substring(nrDig, 1));
                if (nrDig <= 11)
                    soma[0] += (digitos[nrDig] *
                    int.Parse(ftmt.Substring(
                      nrDig + 1, 1)));
                if (nrDig <= 12)
                    soma[1] += (digitos[nrDig] *
                    int.Parse(ftmt.Substring(
                      nrDig, 1)));
            }

            for (nrDig = 0; nrDig < 2; nrDig++)
            {
                resultado[nrDig] = (soma[nrDig] % 11);
                if ((resultado[nrDig] == 0) || (resultado[nrDig] == 1))
                    CNPJOk[nrDig] = (
                    digitos[12 + nrDig] == 0);

                else
                    CNPJOk[nrDig] = (
                    digitos[12 + nrDig] == (
                    11 - resultado[nrDig]));

            }

            return (CNPJOk[0] && CNPJOk[1]);
        }
        catch
        {
            return false;
        }

    }

Method to validate CPF

public bool ValidaCpf(string cpf)
{

    int[] multiplicador1 = new int[9] { 10, 9, 8, 7, 6, 5, 4, 3, 2 };
    int[] multiplicador2 = new int[10] { 11, 10, 9, 8, 7, 6, 5, 4, 3, 2 };
    string tempCpf;
    string digito;

    int soma;
    int resto;

    cpf = cpf.Trim();
    cpf = cpf.Replace(".", "").Replace("-", "");

    if (cpf.Length != 11)
    {
        return false;
    }
    tempCpf = cpf.Substring(0, 9);

    soma = 0;

    for (int i = 0; i < 9; i++)
    {
        soma += int.Parse(tempCpf[i].ToString()) * (multiplicador1[i]);
    }
    resto = soma % 11;

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

    digito = resto.ToString();
    tempCpf = tempCpf + digito;
    int soma2 = 0;

    for (int i = 0; i < 10; i++)
    {
        soma2 += int.Parse(tempCpf[i].ToString()) * multiplicador2[i];
    }

    resto = soma2 % 11;

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

    digito = digito + resto.ToString();
    return cpf.EndsWith(digito);
}
  • I don’t understand why you want to give this information to the user. The check digits serve to confirm that there was no mistake when typing any of the CNPJ digits and not just the last two. What I think you’re suggesting is you want to tell the user to change the last two digits. The CNPJ will be valid but certainly not the user.

  • Yes @ramaral, I would like to tell the user to change the last two digits, but I thought I would tell him which ones would be the right ones. Of course so the guy will be able to swindle the system with cnpj that doesn’t exist, but it’s just one more option that I would like to make available to him. And learning too!

  • @Emersonmoraes, you talk about every question in CNPJ, but your example is CPF, I recommend replacing where you cite CNPJ by CPF, or vice versa.

  • Sorry @Fernando, I just copied the wrong code. I’ll put the CNPJ tbm!

2 answers

2


While not seeing much use in your final implementation, as quoted from @ramaral comments, I’ll help you with the problem itself.

You can use the parameters out of C#, to retrieve the checker digits from the validation method, where the implementation would look something like this (there are comments on the changed lines):

// adicione o paramêtro out string dv
public bool ValidaCpf(string cpf, out string dv)
{
    int[] multiplicador1 = new int[9] { 10, 9, 8, 7, 6, 5, 4, 3, 2 };
    int[] multiplicador2 = new int[10] { 11, 10, 9, 8, 7, 6, 5, 4, 3, 2 };
    string tempCpf;
    string digito;

    int soma;
    int resto;

    cpf = cpf.Trim();
    cpf = cpf.Replace(".", "").Replace("-", "");

    if (cpf.Length != 11)
    {
        // adicione essa linha, onde você seta o parâmetro out dv, com null, para fins de compilação, já que não há valor a ser adicionado, ou se acha melhor pode adicionar qualquer outro valor default.
        dv = null;
        return false;
    }
    tempCpf = cpf.Substring(0, 9);

    soma = 0;

    for (int i = 0; i < 9; i++)
    {
        soma += int.Parse(tempCpf[i].ToString()) * (multiplicador1[i]);
    }
    resto = soma % 11;

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

    digito = resto.ToString();
    tempCpf = tempCpf + digito;
    int soma2 = 0;

    for (int i = 0; i < 10; i++)
    {
        soma2 += int.Parse(tempCpf[i].ToString()) * multiplicador2[i];
    }

    resto = soma2 % 11;

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

    digito = digito + resto.ToString();

    // adicione essa linha, onde você seta o parâmetro out dv, com o digito verificador valido
    dv = digito;
    return cpf.EndsWith(digito);
}

Where an example of use would be:

public void TestUtilizacao()
{
    string dv = null;
    string cpf = "12345678901";
    if(ValidaCpf(cpf, out dv))
    {
        MessageBox.Show("CPF valido");
    }else
    {
        MessageBox.Show("CPF inválido, o Digito Verificador correto seria: " + dv);
    }
}

The use test result would be "Invalid CPF, the correct Digit Checker would be: 09".

  • The CNPJ is the same thing neh...?

  • @Emersonmoraes, yes same idea, I just did not identify your digit checked in your CNPJ validation method. (It seems to me a bit curled, hehe)

  • 1

    I got them both... The CNPJ is the same basis as you did the CPF. Thank you very much for the xD help

1

public static bool IsCnpj(string cnpj)
    {
        int[] multiplicador1 = new int[12] {5,4,3,2,9,8,7,6,5,4,3,2};
        int[] multiplicador2 = new int[13] {6,5,4,3,2,9,8,7,6,5,4,3,2};
        int soma;
        int resto;
        string digito;
        string tempCnpj;

        cnpj = cnpj.Trim();
        cnpj = cnpj.Replace(".", "").Replace("-", "").Replace("/", "");

        if (cnpj.Length != 14)
           return false;

        tempCnpj = cnpj.Substring(0, 12);

        soma = 0;
        for(int i=0; i<12; i++)
           soma += int.Parse(tempCnpj[i].ToString()) * multiplicador1[i];

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

        digito = resto.ToString();

        tempCnpj = tempCnpj + digito;
        soma = 0;
        for (int i = 0; i < 13; i++)
           soma += int.Parse(tempCnpj[i].ToString()) * multiplicador2[i];

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

        digito = digito + resto.ToString();

        if cnpj.Right(2) <> digito
           MsgBox("CNPJ inválido, o Digito Verificador correto seria: "+digito);

        return cnpj.EndsWith(digito);
    }

Browser other questions tagged

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