Skip to content

Instantly share code, notes, and snippets.

@macintoxic
Last active November 6, 2023 04:43
Show Gist options
  • Save macintoxic/d73ec2bbeef9ac5a2d9f04abfce73167 to your computer and use it in GitHub Desktop.
Save macintoxic/d73ec2bbeef9ac5a2d9f04abfce73167 to your computer and use it in GitHub Desktop.
Classe com métodos para validação de CPF e CNPJ utilizando Linq
/// <summary>
/// Classe com métodos para validação de CPF e CNPJ utilizando Linq
/// </summary>
public static class CpfCnpjUtils
{
private static readonly int[] Multiplicador1Cnpj = { 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2 };
private static readonly int[] Multiplicador2Cnpj = { 6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2 };
private static readonly int[] Multiplicador1Cpf = { 10, 9, 8, 7, 6, 5, 4, 3, 2 };
private static readonly int[] Multiplicador2Cpf = { 11, 10, 9, 8, 7, 6, 5, 4, 3, 2 };
/// <summary>
/// Recebe um CPF ou CNPJ para validação.
/// </summary>
/// <param name="cpfCnpj">CPF ou CNPJ</param>
/// <returns>bool</returns>
public static bool IsValid(this string cpfCnpj)
{
//retorna somente digitos
cpfCnpj = new string(cpfCnpj.Where(c => c >= 48 && c < 58).ToArray());
return IsCpf(cpfCnpj) || IsCnpj(cpfCnpj);
}
/// <summary>
/// Verifica se o cpf informado é válido
/// </summary>
/// <param name="cpf"></param>
/// <returns></returns>
private static bool IsCpf(string cpf)
{
if (cpf.Length != 11 || cpf.All(c => c == cpf[0])) return false;
var firstDigit = ComputeDigit(cpf, Multiplicador1Cpf);
var secondDigit = ComputeDigit(cpf, Multiplicador2Cpf);
return cpf.EndsWith($"{firstDigit}{secondDigit}");
}
/// <summary>
/// Verifica se o CNPJ informado é válido.
/// </summary>
/// <param name="cnpj"></param>
/// <returns></returns>
private static bool IsCnpj(string cnpj)
{
if (cnpj.Length != 14 || cnpj.All(c => c == cnpj[0]))
return false;
var firstDigit = ComputeDigit(cnpj, Multiplicador1Cnpj);
var secondDigit = ComputeDigit(cnpj, Multiplicador2Cnpj);
return cnpj.EndsWith($"{firstDigit}{secondDigit}");
}
/// <summary>
/// Calcula o dígito verificador
/// </summary>
/// <param name="cpfOrCnpj">Cpf/Cnpj</param>
/// <param name="multiplicador">Array com os pesos para multipliação.</param>
/// <returns></returns>
private static int ComputeDigit(string cpfOrCnpj, IEnumerable<int> multiplicador)
{
var digit = multiplicador.Select((t, i) => (cpfOrCnpj[i] - 48) * t).Sum() % 11;
return digit < 2 ? 0 : 11 - digit;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment