Skip to content

Instantly share code, notes, and snippets.

@lucaspiressimao
Created August 19, 2020 15:04
Show Gist options
  • Save lucaspiressimao/7cc4858095209c31f45c646d011fa0fd to your computer and use it in GitHub Desktop.
Save lucaspiressimao/7cc4858095209c31f45c646d011fa0fd to your computer and use it in GitHub Desktop.
Validar CNPJ em js
validateCNPJ = cnpj => {
function getDV(value) {
let regDigits = (value.split('')).reverse()
let mod1 = getModule(regDigits)
let mod2 = getModule([mod1,...regDigits])
return `${mod1}${mod2}`
}
function getModule(value) {
let weights = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
let reversed = weights.reverse()
let sum = sumValues(value, reversed)
let mod = sum % 11
return mod < 2 ? 0 : 11 - mod
}
function sumValues(values, weights) {
let sum = 0
for (let i = 0; i < values.length; i++) {
const element = values[i];
sum += element * weights[i]
}
return sum
}
cnpj = ('' + cnpj).replace(/\D/g, '')
if (cnpj.length != 14) return false
let verificationDigit = cnpj.slice(12, 14)
let registration = cnpj.slice(0, 12)
let dv = getDV(registration)
return dv == verificationDigit
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment