Skip to content

Instantly share code, notes, and snippets.

@TiagoGouvea
Created September 19, 2016 12:53
Show Gist options
  • Save TiagoGouvea/eceb100ae9c5addfe46884ed711e12e5 to your computer and use it in GitHub Desktop.
Save TiagoGouvea/eceb100ae9c5addfe46884ed711e12e5 to your computer and use it in GitHub Desktop.
Validar e formatar CPF
public static string SomenteNumeros(string texto = null)
{
if (texto == null) return texto;
Regex re = new Regex("[0-9]");
StringBuilder s = new StringBuilder();
foreach (Match m in re.Matches(texto))
{
s.Append(m.Value);
}
return s.ToString();
}
public static string FormatarCpf(string cpf = null)
{
if (cpf == null || cpf.Length < 11) return null;
cpf = SomenteNumeros(cpf);
if (cpf.Length != 11) return null;
return cpf.Substring(0, 3) + "." + cpf.Substring(3, 3) + "." + cpf.Substring(6, 3) + "-" + cpf.Substring(9, 2);
}
public static bool ValidarCpf(string cpf)
{
if (cpf == null) return false;
cpf = SomenteNumeros(cpf);
if (cpf.Length != 11) return false;
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;
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;
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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment