Skip to content

Instantly share code, notes, and snippets.

@carlosdaniiel07
Last active August 21, 2023 22:34
Show Gist options
  • Save carlosdaniiel07/55c70649c5a60abf08e3d8f584b2d9af to your computer and use it in GitHub Desktop.
Save carlosdaniiel07/55c70649c5a60abf08e3d8f584b2d9af to your computer and use it in GitHub Desktop.
Validação chave de acesso (digito verificador) - Nota Fiscal. Função criada a partir do script PHP: https://www.codigofonte.com.br/codigos/aprenda-a-calcular-o-digito-verificador-da-chave-de-nfe
const isValid = chaveAcesso => {
if (!chaveAcesso || chaveAcesso.trim().length !== 44) {
return false
}
const chaveParcial = chaveAcesso.substring(0, 43)
const multiplicadores = [2, 3, 4, 5, 6, 7, 8, 9]
let i = 42
let somaPonderada = 0
while (i >= 0) {
for (let j = 0; (j < multiplicadores.length && i >= 0); j++) {
somaPonderada += chaveParcial[i] * multiplicadores[j]
i -= 1
}
}
const resto = somaPonderada % 11
const dv = (resto === 0 || resto === 1) ? 0 : 11 - resto
return String(dv) === chaveAcesso.substring(43, 44)
}
// Example
console.log(isValid('CHAVE_DE_ACESSO_COM_44_CARACTERES'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment