-1
I need a help I have a CPF validation class in C# in a registration API project, but I don’t know how to implement this function to work validation, I’m using Microsoft to add the function in command ? controller? any help ?
here’s my validation class
public class ValidaCPF
{
public Int64 Codigo_Cpf { get; set; }
public void ValidandoCpf(string cpf)
{
try
{
cpf = CpfLimpo(cpf);
if (!IsCpfValido(cpf))
throw new Exception();
Codigo_Cpf = Convert.ToInt64(cpf);
}
catch (Exception)
{
throw new Exception("CPF inválido: " + cpf);
}
}
public string GetSemZeros()
{
return Codigo_Cpf.ToString();
}
public static string CpfLimpo(string cpf)
{
cpf = GetNumeros(cpf);
if (string.IsNullOrEmpty(cpf))
return "";
while (cpf.StartsWith("0"))
cpf = cpf.Substring(1);
return cpf;
}
public static string GetNumeros(string texto_contendo_cpf)
{
return string.IsNullOrEmpty(texto_contendo_cpf) ? "" : new String(texto_contendo_cpf.Where(Char.IsDigit).ToArray());
}
public string GetCpfCompleto()
{
var cpf = Codigo_Cpf.ToString();
if (string.IsNullOrEmpty(cpf))
return "";
while (cpf.Length < 11)
cpf = "0" + cpf;
return cpf;
}
public static bool IsCpfValido(string cpf)
{
while (cpf.Length < 11)
cpf = "0" + cpf;
var multiplicador1 = new[] { 10, 9, 8, 7, 6, 5, 4, 3, 2 };
var multiplicador2 = new[] { 11, 10, 9, 8, 7, 6, 5, 4, 3, 2 };
cpf = cpf.Trim();
cpf = cpf.Replace(".", "").Replace("-", "").Replace("/", "");
if (cpf.Length != 11)
return false;
var CpfTemporario = cpf.Substring(0, 9);
var soma = 0;
for (var i = 0; i < 9; i++)
soma += int.Parse(CpfTemporario[i].ToString()) * multiplicador1[i];
var resto = soma % 11;
if (resto < 2)
resto = 0;
else resto = 11 - resto;
var digito = resto.ToString();
CpfTemporario = CpfTemporario + digito;
soma = 0;
for (var i = 0; i < 10; i++)
soma += int.Parse(CpfTemporario[i].ToString()) * multiplicador2[i];
resto = soma % 11;
if (resto < 2)
resto = 0;
else resto = 11 - resto;
digito = digito + resto;
return cpf.EndsWith(digito);
}
}
}