Inicial
> Dicas / Tips > Validar CPF em C#
Validar CPF em C#
Mais uma dica no estilo: Copiar, colar e utilizar.
public static bool ValidaCpf(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 }; string tempCpf; string digito; int soma; int resto; cpf = cpf.Trim(); cpf = cpf.Replace(".", "").Replace("-", ""); if (cpf.Length != 11) { return false; } 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; int soma2 = 0; for (int i = 0; i < 10; i++) { soma2 += int.Parse(tempCpf[i].ToString()) * multiplicador2[i]; } resto = soma2 % 11; if (resto < 2) { resto = 0; } else { resto = 11 - resto; } digito = digito + resto.ToString(); return cpf.EndsWith(digito); }
Caso o meu CPF seja de 9 digitos (antigos CPF’s), como ficaria isso?, tendo em vista que logo no inicio tenho esse validação caso seja diferente de 11 ira retornar false e sair da função.
if (cpf.Length != 11)
{
return false;
}
tem algum solução para isso?
Não sabia que houveram CPF de 9 dígitos hehe…
Como a validação está totalmente vinculada ao length, tem que acrescentar um outro condicional nesse IF.
Pesquisando sobre o assunto parece que nem o ENEM tá com suporte a CPF 9 dígitos:
https://br.answers.yahoo.com/question/index?qid=20120613172629AAJGuEe