Skip to content

Instantly share code, notes, and snippets.

@joaohcrangel
Last active June 25, 2024 15:16
Show Gist options
  • Save joaohcrangel/8bd48bcc40b9db63bef7201143303937 to your computer and use it in GitHub Desktop.
Save joaohcrangel/8bd48bcc40b9db63bef7201143303937 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];
}
@bestknighter
Copy link

Precisei dessa função novamente em outro projeto. Só que nele eu tbm precisava da função que gerava o dígito verificador em outros lugares do código. Lá eu transformei ela num método funcional puro e extraí para o mesmo módulo. Apliquei a mesma mudança aqui mas mantive dentro da função para não poluir o escopo.

function isValidCPF(value: string) {
    // Se não for string, o CPF é inválido
    if (typeof value !== 'string') {
        return false;
    }

    // Remove todos os caracteres que não sejam números
    value = value.replace(/[^\d]+/g, '');

    // Se o CPF não tem 11 dígitos ou todos os dígitos são repetidos, o CPF é inválido
    if (value.length !== 11 || !!value.match(/(\d)\1{10}/)) {
        return false;
    }
    
    // Transforma de string para number[] com cada dígito sendo um número no array
    const digits = value.split('').map(el => +el);

    // Função que calcula o dígito verificador de acordo com a fórmula da Receita Federal
    function getVerifyingDigit(arr: number[]) {
        const reduced = arr.reduce( (sum, digit, index)=>(sum + digit * (arr.length - index + 1)), 0 );
        return (reduced * 10) % 11 % 10;
    }

    // O CPF é válido se, e somente se, os dígitos verificadores estão corretos
    return getVerifyingDigit(digits.slice(0, 9)) === digits[9]
        && getVerifyingDigit(digits.slice(0, 10)) === digits[10];
}

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