Skip to content

Instantly share code, notes, and snippets.

@brunoconstantino
Created October 29, 2024 05:03
Show Gist options
  • Save brunoconstantino/ddfe29cf084a6dbdf1d3f14385fe09e9 to your computer and use it in GitHub Desktop.
Save brunoconstantino/ddfe29cf084a6dbdf1d3f14385fe09e9 to your computer and use it in GitHub Desktop.
Validador de CNPJ alfa-numérico em Javascript
/**
* Valida um CNPJ com 14 caracteres, onde os 12 primeiros podem ser alfanuméricos e os 2 últimos são dígitos verificadores.
* A validação é feita utilizando o método do módulo 11, e para caracteres alfabéticos o valor ASCII é subtraído por 48.
*
* @link http://normas.receita.fazenda.gov.br/sijut2consulta/link.action?idAto=141102
* @param string $cnpj O CNPJ a ser validado, com 14 caracteres alfanuméricos (12 primeiros) e numéricos (2 últimos).
* @return bool Retorna true se o CNPJ for válido, false caso contrário.
* @author Bruno Constantino
* @date 2024-10-29
*/
function isCNPJ(cnpj) {
const b = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
const c = cnpj.toUpperCase().replace(/[^A-Z0-9]/g, '');
if (c.length !== 14 || /^0{14}$/.test(c)) return false;
const getCharValue = char => char >= 'A' ? char.charCodeAt(0) - 48 : +char;
const checkDigit = pos => {
let n = c.slice(0, pos).split('').reduce((sum, char, i) => sum + getCharValue(char) * b[i + (pos === 12)], 0);
return c[pos] == ((n %= 11) < 2 ? 0 : 11 - n);
};
return checkDigit(12) && checkDigit(13);
}
console.log( isCNPJ("00.000.000/0001-91") );
console.log( isCNPJ("59.952.259/0001-85") );
console.log( isCNPJ("12ABC34501DE35") );
console.log( isCNPJ("12aBc34501DE35") );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment