Learn To Check Is A CNPJ Is Valid

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

The mask for input is 99.999.999/9999-99.

The last two digits are based on a formula.

There are no duplicated CNPs in Brazil, every legal entity in Brazil has its own, and he needs to open a bank account, trade, and get public services.

Here is a function that I use in my projects,

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

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

if (ValidarCNPJ("11111111111112")) {
    return "CNPJ is ok!";
} else {
    return "CNPJ is invalid!";
}


Similar Articles