Skip to content

Instantly share code, notes, and snippets.

@mhef
Created May 4, 2020 12:38
Show Gist options
  • Save mhef/304925ddd5ba2f66e2b90cf6a7db8051 to your computer and use it in GitHub Desktop.
Save mhef/304925ddd5ba2f66e2b90cf6a7db8051 to your computer and use it in GitHub Desktop.
Validar CPF e CNPJ - Javascript ES6
/**
@author github.com/mhef
*/
const validateCPF = (cpf) => {
if (cpf.length != 11) return false;
let expanded = [...cpf];
let expandedWC = expanded.slice(0,9); // without check digits
if(expanded.every(v => v == cpf[0])) return false; // fail if all numbers are equal
let firstSum = expandedWC.reduce((acc, cur, idx) => acc + ((10-idx) * parseInt(cur)), 0);
let firstDigit = ((firstSum % 11) < 2 ? 0 : 11 - (firstSum % 11));
let expandedWF = [...expandedWC, firstDigit]; // with first digit
let secondSum = expandedWF.reduce((acc, cur, idx) => acc + ((11-idx) * parseInt(cur)), 0);
let secondDigit = ((secondSum % 11) < 2 ? 0 : 11 - (secondSum % 11));
return firstDigit == expanded[9] && secondDigit == expanded[10];
}
const validateCNPJ = (cnpj) => {
let weights = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
if (cnpj.length != 14) return false;
let expanded = [...cnpj];
let expandedWC = expanded.slice(0,12); // without check digits
if(expanded.every(v => v == cnpj[0])) return false; // fail if all numbers are equal
let firstSum = expandedWC.reduce((acc, cur, idx) => acc + (weights[idx+1] * parseInt(cur)), 0);
let firstDigit = ((firstSum % 11) < 2 ? 0 : 11 - (firstSum % 11));
let expandedWF = [...expandedWC, firstDigit]; // with first digit
let secondSum = expandedWF.reduce((acc, cur, idx) => acc + (weights[idx] * parseInt(cur)), 0);
let secondDigit = ((secondSum % 11) < 2 ? 0 : 11 - (secondSum % 11));
return firstDigit == expanded[12] && secondDigit == expanded[13];
}
@felipeasimos
Copy link

validador de CPF quebrou o galho aqui, obrigado por compartilhar! :)

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