Created
May 29, 2018 14:22
-
-
Save antonyalkmim/a6ced28c6a10e7692c08381e9f985e5a to your computer and use it in GitHub Desktop.
Script javascript para verificar se CPF e CNPJ são válidos.
This file contains hidden or 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
const calcularDigito = (str, peso) => { | |
var soma = 0; | |
var indice = str.length - 1; | |
var digito; | |
while (indice >= 0) { | |
digito = parseInt(str.substring(indice, indice + 1)); | |
soma += digito * peso[peso.length - str.length + indice]; | |
indice-- | |
} | |
soma = 11 - soma % 11; | |
return soma > 9 ? 0 : soma; | |
}; | |
const isValidCPF = (cpfStr) => { | |
const cpf = cpfStr.replace(/[^0-9]+/g, ""); | |
const nums = cpf.split("").map(it => parseInt(it)).sort(); | |
if (cpf.length != 11 || nums[0] == nums[10]) return false; | |
const pesoCPF = [11, 10, 9, 8, 7, 6, 5, 4, 3, 2]; | |
const digito1 = calcularDigito(cpf.substring(0, 9), pesoCPF); | |
const digito2 = calcularDigito(cpf.substring(0, 9) + digito1, pesoCPF); | |
return cpf == cpf.substring(0, 9) + digito1.toString() + digito2.toString(); | |
}; | |
const isValidCNPJ = (cnpjStr) => { | |
const cnpj = cnpjStr.replace(/[^0-9]+/g, ""); | |
if (cnpj.length != 14) return false; | |
const pesoCNPJ = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]; | |
const digito1 = calcularDigito(cnpj.substring(0, 12), pesoCNPJ); | |
const digito2 = calcularDigito(cnpj.substring(0, 12) + digito1, pesoCNPJ); | |
return cnpj == cnpj.substring(0, 12) + digito1.toString() + digito2.toString(); | |
}; | |
const isValidCPForCNPJ = (cpfCnpj) => isValidCPF(cpfCnpj) || isValidCNPJ(cpfCnpj); | |
module.exports = { | |
isValidCPForCNPJ : isValidCPForCNPJ, | |
isValidCPF: isValidCPF, | |
isValidCNPJ: isValidCNPJ | |
}; | |
// Usage | |
// const CPFCNPJ = require("./CPFnCNPJUtils.js") | |
// CPFCNPJ.isValidCPF("123.456.789-09") // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment