Last active
September 21, 2021 01:36
-
-
Save willnss/a657f0f9a7ceddb14b83bdc70b1e4d39 to your computer and use it in GitHub Desktop.
Classe de exemplo para o amigo Ademir
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment