Created
August 14, 2017 21:02
-
-
Save rdakar/dba890b5e2cbdeb7c62c0dee9f627a7f to your computer and use it in GitHub Desktop.
Validação de CPF e CNPJ - C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace CpfCnpj | |
{ | |
public static class CpfCnpjUtils | |
{ | |
public static bool IsValid(string cpfCnpj) | |
{ | |
return (IsCpf(cpfCnpj) || IsCnpj(cpfCnpj)); | |
} | |
private static bool IsCpf(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 }; | |
cpf = cpf.Trim().Replace(".", "").Replace("-", ""); | |
if (cpf.Length != 11) | |
return false; | |
for (int j = 0; j < 10; j++) | |
if (j.ToString().PadLeft(11, char.Parse(j.ToString())) == cpf) | |
return false; | |
string tempCpf = cpf.Substring(0, 9); | |
int soma = 0; | |
for (int i = 0; i < 9; i++) | |
soma += int.Parse(tempCpf[i].ToString()) * multiplicador1[i]; | |
int resto = soma % 11; | |
if (resto < 2) | |
resto = 0; | |
else | |
resto = 11 - resto; | |
string digito = resto.ToString(); | |
tempCpf = tempCpf + digito; | |
soma = 0; | |
for (int i = 0; i < 10; i++) | |
soma += int.Parse(tempCpf[i].ToString()) * multiplicador2[i]; | |
resto = soma % 11; | |
if (resto < 2) | |
resto = 0; | |
else | |
resto = 11 - resto; | |
digito = digito + resto.ToString(); | |
return cpf.EndsWith(digito); | |
} | |
private 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 }; | |
cnpj = cnpj.Trim().Replace(".", "").Replace("-", "").Replace("/", ""); | |
if (cnpj.Length != 14) | |
return false; | |
string tempCnpj = cnpj.Substring(0, 12); | |
int soma = 0; | |
for (int i = 0; i < 12; i++) | |
soma += int.Parse(tempCnpj[i].ToString()) * multiplicador1[i]; | |
int resto = (soma % 11); | |
if (resto < 2) | |
resto = 0; | |
else | |
resto = 11 - resto; | |
string 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(); | |
return cnpj.EndsWith(digito); | |
} | |
} | |
} |
Obrigado! Serviu perfeitamente.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
<3