Last active
June 29, 2021 13:04
-
-
Save BrunoDSouza/c78ab4075c4148d4cd34aecdaef4bb64 to your computer and use it in GitHub Desktop.
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
public bool IsValidCPF(string value) | |
{ | |
if (value == null) | |
return false; | |
value = value.NormalizeString(); | |
if (value.Length != 11) | |
return false; | |
var cpf = value.Select(c => c.ToInt()).ToList(); | |
var m1 = cpf.Take(9).Select((e, i) => e * (11 - (i + 1))).Sum() % 11; | |
if (cpf[9] != ((m1 == 0 || m1 == 1) ? 0 : 11 - m1)) | |
return false; | |
var m2 = cpf.Take(10).Select((e, i) => e * (11 - i)).Sum() % 11; | |
if (cpf[10] != ((m2 == 0 || m2 == 1) ? 0 : 11 - m2)) | |
return false; | |
return true; | |
} | |
public static bool IsValidCNPJ(string value) | |
{ | |
if (string.IsNullOrEmpty(value)) | |
return false; | |
Func<int, int> func = somatorio => (somatorio % 11) < 2 ? 0 : 11 - (somatorio % 11); | |
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 }; | |
value = value.Trim().Replace(".", "").Replace("-", "").Replace("/", ""); | |
if (value.Length != 14) | |
return false; | |
var cnpj = value.Trim().Replace(".", "").Replace("-", "").Replace("/", ""); | |
if (cnpj.Length != 14) | |
return ValueResult.Failure(); | |
var cnpjBase = cnpj.Take(12).Select(c => int.Parse(c.ToString())).ToArray(); | |
var soma = multiplicador1.Select((x, index) => cnpjBase[index] * x).Sum(); | |
var resto = func(soma); | |
var cnpjBaseComDigito = cnpjBase.Concat(new[] { resto }).ToArray(); | |
var soma2 = multiplicador2.Select((x, index) => cnpjBaseComDigito[index] * x).Sum(); | |
var resto2 = func(soma2); | |
var digito = $"{resto}{resto2}"; | |
if (cnpj.EndsWith(digito.ToString())) | |
return true; | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment