Skip to content

Instantly share code, notes, and snippets.

@leandrodaher
Forked from joaohcrangel/validation-cpf.ts
Created April 19, 2023 01:17
Show Gist options
  • Save leandrodaher/23568e0ca58b015628a7abd3b03b7e14 to your computer and use it in GitHub Desktop.
Save leandrodaher/23568e0ca58b015628a7abd3b03b7e14 to your computer and use it in GitHub Desktop.
Função para validar CPF em TypeScript
function isValidCPF(value: string) {
if (typeof value !== 'string') {
return false;
}
value = value.replace(/[^\d]+/g, '');
if (value.length !== 11 || !!value.match(/(\d)\1{10}/)) {
return false;
}
const values = value.split('').map(el => +el);
const rest = (count) => (values.slice(0, count-12).reduce( (soma, el, index) => (soma + el * (count-index)), 0 )*10) % 11 % 10;
return rest(10) === values[9] && rest(11) === values[10];
}
@leandrodaher
Copy link
Author

jaronwanderley commented on Jun 15, 2021

Tenho uma sugestão usando paradigma funcional, e um pouco mais reduzido 🤓

function isValidCPF(cpf) {
    if (typeof cpf !== 'string') return false
    cpf = cpf.replace(/[^\d]+/g, '')
    if (cpf.length !== 11 || !!cpf.match(/(\d)\1{10}/)) return false
    cpf = cpf.split('')
    const validator = cpf
        .filter((digit, index, array) => index >= array.length - 2 && digit)
        .map( el => +el )
    const toValidate = pop => cpf
        .filter((digit, index, array) => index < array.length - pop && digit)
        .map(el => +el)
    const rest = (count, pop) => (toValidate(pop)
        .reduce((soma, el, i) => soma + el * (count - i), 0) * 10) % 11 % 10
    return !(rest(10,2) !== validator[0] || rest(11,1) !== validator[1])
}

Pra quem quer entender:

function isValidCPF(cpf) {
    // Validar se é String
    if (typeof cpf !== 'string') return false
    
    // Tirar formatação
    cpf = cpf.replace(/[^\d]+/g, '')
    
    // Validar se tem tamanho 11 ou se é uma sequência de digitos repetidos
    if (cpf.length !== 11 || !!cpf.match(/(\d)\1{10}/)) return false
    
    // String para Array
    cpf = cpf.split('')
    
    const validator = cpf
        // Pegar os últimos 2 digitos de validação
        .filter((digit, index, array) => index >= array.length - 2 && digit)
        // Transformar digitos em números
        .map( el => +el )
        
    const toValidate = pop => cpf
        // Pegar Array de items para validar
        .filter((digit, index, array) => index < array.length - pop && digit)
        // Transformar digitos em números
        .map(el => +el)
    
    const rest = (count, pop) => (toValidate(pop)
        // Calcular Soma dos digitos e multiplicar por 10
        .reduce((soma, el, i) => soma + el * (count - i), 0) * 10) 
        // Pegar o resto por 11
        % 11 
        // transformar de 10 para 0
        % 10
        
    return !(rest(10,2) !== validator[0] || rest(11,1) !== validator[1])
}

Esta função já retorna um booleano (verdadeiro ou falso), logo não precisa comparar dentro de um condicional (if)... só chamar a função!

if ( isValidCPF(cpf) ) // só executa se for cpf válido

if ( !isValidCPF(cpf) ) // só executa se não for um cpf válido

@leandrodaher
Copy link
Author

bestknighter commented on Dec 24, 2021

Ainda mais simplificado kkk

function isValidCPF(cpf) {
    if (typeof cpf !== 'string') return false
    cpf = cpf.replace(/[^\d]+/g, '')
    if (cpf.length !== 11 || !!cpf.match(/(\d)\1{10}/)) return false
    cpf = cpf.split('').map(el => +el)
    const rest = (count) => (cpf.slice(0, count-12)
        .reduce( (soma, el, index) => (soma + el * (count-index)), 0 )*10) % 11 % 10
    return rest(10) === cpf[9] && rest(11) === cpf[10]
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment