Last active
June 11, 2023 20:21
-
-
Save gabrielfreirebraz/cc2103dd6b4f206cba3fd9a8c0d98331 to your computer and use it in GitHub Desktop.
Validar CNPJ se o cálculo é válido
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 cnpjValidation = (value) => { | |
if (!value) return false | |
// Aceita receber o valor como string, número ou array com todos os dígitos | |
const isString = typeof value === 'string' | |
const validTypes = isString || Number.isInteger(value) || Array.isArray(value) | |
// Elimina valor de tipo inválido | |
if (!validTypes) return false | |
// Filtro inicial para entradas do tipo string | |
if (isString) { | |
// Limita ao mínimo de 14 caracteres, válido para apenas dígitos | |
// Limita ao máximo de 18 caracteres, válido para CNPJ formatado | |
// Se passar dos limites, retorna inválido | |
if (value.length < 14 || value.length > 18) return false | |
// Teste Regex para veificar se é uma string apenas dígitos válida | |
const digitsOnly = /^\d{14}$/.test(value) | |
// Teste Regex para verificar se é uma string formatada válida | |
const validFormat = /^\d{2}.\d{3}.\d{3}\/\d{4}-\d{2}$/.test(value) | |
// Verifica se o valor passou em ao menos 1 dos testes | |
const isValid = digitsOnly || validFormat | |
// Se o formato não é válido, retorna inválido | |
if (!isValid) return false | |
} | |
// Guarda um array com todos os dígitos do valor | |
const match = value.toString().match(/\d/g) | |
const numbers = Array.isArray(match) ? match.map(Number) : [] | |
// Valida a quantidade de dígitos | |
if (numbers.length !== 14) return false | |
// Elimina inválidos com todos os dígitos iguais | |
const items = [...new Set(numbers)] | |
if (items.length === 1) return false | |
// Cálculo validador | |
const calc = (x) => { | |
const slice = numbers.slice(0, x) | |
let factor = x - 7 | |
let sum = 0 | |
for (let i = x; i >= 1; i--) { | |
const n = slice[x - i] | |
sum += n * factor-- | |
if (factor < 2) factor = 9 | |
} | |
const result = 11 - (sum % 11) | |
return result > 9 ? 0 : result | |
} | |
// Separa os 2 últimos dígitos de verificadores | |
const digits = numbers.slice(12) | |
// Valida 1o. dígito verificador | |
const digit0 = calc(12) | |
if (digit0 !== digits[0]) return false | |
// Valida 2o. dígito verificador | |
const digit1 = calc(13) | |
return digit1 === digits[1] | |
// Referência: https://pt.wikipedia.org/wiki/Cadastro_Nacional_da_Pessoa_Jur%C3%ADdica | |
// Autor do código: https://gist.github.com/alexbruno | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Autor do código: @alexbruno