Skip to content

Instantly share code, notes, and snippets.

@leonardodepaula
Created September 22, 2021 15:43
Show Gist options
  • Save leonardodepaula/fe932846a03a77afe2d01466a27c18b4 to your computer and use it in GitHub Desktop.
Save leonardodepaula/fe932846a03a77afe2d01466a27c18b4 to your computer and use it in GitHub Desktop.
# Django
from django.core.exceptions import ValidationError
# Validaddor de CPF
def valida_cpf(cpf: str):
# Obtém apenas os números do CPF, ignorando pontuações
numbers = [int(digit) for digit in cpf if digit.isdigit()]
# Verifica se o CPF possui 11 números ou se todos são iguais:
if len(numbers) != 11 or len(set(numbers)) == 1:
raise ValidationError(f'{cpf} não é um CPF válido.')
# Validação do primeiro dígito verificador:
sum_of_products = sum(a*b for a, b in zip(numbers[0:9], range(10, 1, -1)))
expected_digit = (sum_of_products * 10 % 11) % 10
if numbers[9] != expected_digit:
raise ValidationError(f'{cpf} não é um CPF válido.')
# Validação do segundo dígito verificador:
sum_of_products = sum(a*b for a, b in zip(numbers[0:10], range(11, 1, -1)))
expected_digit = (sum_of_products * 10 % 11) % 10
if numbers[10] != expected_digit:
raise ValidationError(f'{cpf} não é um CPF válido.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment