Last active
September 21, 2021 01:36
-
-
Save willnss/a657f0f9a7ceddb14b83bdc70b1e4d39 to your computer and use it in GitHub Desktop.
Revisions
-
Willianns revised this gist
Sep 21, 2021 . No changes.There are no files selected for viewing
-
Willianns created this gist
Sep 21, 2021 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal 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); } }