Skip to content

Instantly share code, notes, and snippets.

@guilhermewebdev
Last active November 20, 2020 01:02
Show Gist options
  • Save guilhermewebdev/ef264f1c06484eb3e483e9a3cf403d0b to your computer and use it in GitHub Desktop.
Save guilhermewebdev/ef264f1c06484eb3e483e9a3cf403d0b to your computer and use it in GitHub Desktop.
Validação de CPF em JavaScript, padrão funcional, ideal para usar com React.js
from django.core.validators import RegexValidator
from functools import reduce
import re
verify_sum = lambda cpf, last_index: reduce(
lambda total, el, index: total + (el * (index + 2)),
cpf.reverse()[0:last_index], 0)
def verify_rest(sum: int, digit: int):
rest = (sum * 10) % 11
new_rest = 0 if ((rest == 10) or (rest == 11)) else rest
return new_rest == digit
def validate_cpf(value: str):
unmasked_cpf = re.sub('[\s.-]*', '', value)
array_cpf = map(lambda el: int(el), value.split(''))
RegexValidator('(\d)\1{10}')(unmasked_cpf)
if (not unmasked_cpf or unmasked_cpf.length != 11):
return False
first_sum = verify_sum(array_cpf, 9)
second_sum = verify_sum(array_cpf, 10)
return verify_rest(first_sum, array_cpf[9]) and verify_rest(second_sum, array_cpf[10])
const verifySum = (cpf: number[], lastIndex: number): number => cpf
.slice(0, lastIndex)
.reverse()
.reduce((total, current, index) => total + (current * (index + 2)), 0);
const verifyRest = (sum: number, digit: number) => {
const rest = (sum * 10) % 11;
const newRest = ((rest == 10) || (rest == 11)) ? 0 : rest;
return newRest == digit;
}
export const validateCPF = (cpf: string) => {
if (typeof cpf !== "string") return false;
const unmaskedCPF = cpf.replace(/[\s.-]*/igm, '');
const arrayCPF = unmaskedCPF.split('').map(value => parseInt(value));
if (
!unmaskedCPF ||
unmaskedCPF.length != 11 ||
/(\d)\1{10}/.test(unmaskedCPF)
) return false;
const firstSum = verifySum(arrayCPF, 9);
const secondSum = verifySum(arrayCPF, 10);
return verifyRest(firstSum, arrayCPF[9]) && verifyRest(secondSum, arrayCPF[10]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment