CNPJ (Cadastro Nacional de Pessoa Jurídica) is a tax identification number assigned to companies and other organizations in Brazil.
To validate a CNPJ (Cadastro Nacional de Pessoa Jurídica), you can follow the following steps:
- Remove all non-numeric characters from the CNPJ, leaving only the digits.
- Check if the CNPJ has exactly 14 digits.
- Check if the CNPJ does not consist of repeated digits (e.g. 11.111.111/1111-11).
- Calculate the first CNPJ verifier digit using a multiplication and sum formula. Compare the calculated digit with the actual digit of the CNPJ.
- Calculate the second CNPJ verifier digit using a multiplication and sum formula. Compare the calculated digit with the actual digit of the CNPJ.
- If the calculated verifier digits match the actual digits of the CNPJ, the CNPJ is valid. Otherwise, the CNPJ is invalid.
In summary, CNPJ validation involves removing non-numeric characters, checking for length and repeated digits, and calculating and comparing verifier digits using multiplication and sum formulas.
Exemple em Javascript code:
function validateCNPJ(cnpj) {
cnpj = cnpj.replace(/[^\d]+/g,'');
if (cnpj.length !== 14) {
return false;
}
if (/^(\d)\1+$/.test(cnpj)) {
return false;
}
let sum = 0;
let multiplier = 2;
for (let i = 11; i >= 0; i--) {
sum += cnpj.charAt(i) * multiplier;
multiplier = (multiplier + 1) % 9 || 2;
}
const firstDigit = (sum % 11) < 2 ? 0 : 11 - (sum % 11);
if (cnpj.charAt(12) != firstDigit) {
return false;
}
sum = 0;
multiplier = 2;
for (let i = 12; i >= 0; i--) {
sum += cnpj.charAt(i) * multiplier;
multiplier = (multiplier + 1) % 9 || 2;
}
const secondDigit = (sum % 11) < 2 ? 0 : 11 - (sum % 11);
if (cnpj.charAt(13) != secondDigit) {
return false;
}
return true;
}