Skip to content

Instantly share code, notes, and snippets.

@willnss
Last active September 21, 2021 01:36
Show Gist options
  • Select an option

  • Save willnss/a657f0f9a7ceddb14b83bdc70b1e4d39 to your computer and use it in GitHub Desktop.

Select an option

Save willnss/a657f0f9a7ceddb14b83bdc70b1e4d39 to your computer and use it in GitHub Desktop.

Revisions

  1. @Willianns Willianns revised this gist Sep 21, 2021. No changes.
  2. @Willianns Willianns created this gist Sep 21, 2021.
    48 changes: 48 additions & 0 deletions CPFAttribute.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,48 @@
    public class CPFAttribute : ValidationAttribute
    {
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
    if (string.IsNullOrEmpty(value)) return new ValidationResult("CPF é obrigatório");

    var cpf = value.ToString().Replace('.', '').Replace('-', '');
    return IsCpf(cpf)
    ? ValidationResult.Success
    : new ValidationResult("CPF inválido!");
    }

    public bool IsCpf(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;
    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);
    }
    }