using System.Linq; namespace SCM.Domain.Qualidade; /// Validação de CPF (dígitos verificadores). Portado de MCQ/AgenteController.cpfValido. public static class CpfValidator { private static readonly int[] Mult1 = { 10, 9, 8, 7, 6, 5, 4, 3, 2 }; private static readonly int[] Mult2 = { 11, 10, 9, 8, 7, 6, 5, 4, 3, 2 }; /// Remove pontuação e retorna apenas os dígitos do CPF. public static string OnlyDigits(string cpf) => new(cpf.Where(char.IsDigit).ToArray()); public static bool IsValid(string? cpf) { if (string.IsNullOrWhiteSpace(cpf)) return false; var digits = OnlyDigits(cpf); if (digits.Length != 11) return false; if (digits.Distinct().Count() == 1) return false; // todos iguais (00000000000, etc.) var temp = digits[..9]; var soma = 0; for (var i = 0; i < 9; i++) soma += (temp[i] - '0') * Mult1[i]; var resto = soma % 11; resto = resto < 2 ? 0 : 11 - resto; var digito = resto.ToString(); temp += digito; soma = 0; for (var i = 0; i < 10; i++) soma += (temp[i] - '0') * Mult2[i]; resto = soma % 11; resto = resto < 2 ? 0 : 11 - resto; digito += resto.ToString(); return digits.EndsWith(digito); } }