c# How to Apply Function to validate Cpf in an API?

Asked

Viewed 56 times

-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);
    }
}

}

1 answer

0

The ideal in my opinion is that you implement an abstract class of service, for example "Baseservice", which will be inherited by all your services, this class will handle all notifications, and you can create a validator to launch notifications, in practical terms it would be something like this:

In the service layer you can create Baseservice:

private readonly INotificator _notificador;

    protected BaseService(INotificator notificador)
    {
        _notificador = notificador;
    }

    protected void Notify(ValidationResult validationResult)
    {
        foreach (var error in validationResult.Errors)
        {
            Notify(error.ErrorMessage);
        }
    }

    protected void Notify(string mensagem)
    {
        _notificador.Handle(new Notification(mensagem));
    }

protected bool ExecuteValidation<TV, TE>(TV validation, TE entity) where TV : AbstractValidator<TE> where TE : EntityBase
    {
        var validator = validation.Validate(entity);

        if (validator.IsValid) return true;

        Notify(validator);

        return false;
    }

This latter method will be responsible for validating anything that is configured in its validation classes, for example Customersvalidation I usually use Fluentvalidation for that.

Customer class

public class ClienteValidation : AbstractValidator<Cliente>
{
    public ClienteValidation ()
    {
        RuleFor(f=> CpfValidacao.Validar(f.Documento)).Equal(true)
                .WithMessage("O documento fornecido é inválido.");
    }
}

Here in this part you will check if the number is correct. And finally in the service you will call the check, assuming you have a method in the service to insert a new customer:

 public async Task<bool> Adicionar(Cliente cliente)
    {
        if (!ExecutarValidacao(new ClienteValidation(), cliente)) return false;

        //....demais partes do código


    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.