Created
June 22, 2018 18:09
-
-
Save franklinbaldo/9691308235a89be72c20a92b67161bb3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function validarCPFouCNPJ (valor){ | |
valor = String(valor).replace(/[^0-9]/g,"").padStart("0",14).substr(0,14); | |
let cnpj = valor.split(""); | |
let cpf = valor.substr(-11).split(""); | |
let mascaras={}; | |
mascaras.cnpj = [6,5,4,3,2,9,8,7,6,5,4,3,2]; | |
mascaras.cpf = [11,10,9,8,7,6,5,4,3,2]; | |
let validar = function (cpfcnpj){ | |
let tipo = (cpfcnpj.length>11)?"cnpj":"cpf"; | |
let dv = cpfcnpj.slice(-2); | |
let calculateDv = dv.map((v,i)=>((11-cpfcnpj.slice(0,-2+i).map((e,b,c)=>mascaras[tipo][b+1-i]*e).reduce( (a, b) => a + b)%11)+"").substr(-1)); | |
return calculateDv.join() === dv.join(); | |
} | |
return validar(cpf) ||validar(cnpj); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment