JSFiddle - React, Tailwind, and code Playground
JavaScript
function CNPJValidator(cnpj){
function getVerificationCode1(){
var total = 0;
var mod = 0;
var factors = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
var nums = this.cnpj.substr(0,12).split('');
for( var i in nums){
total += nums[i]*factors[i];
}
mod = total%11;
return ( mod < 2) ? 0 : 11 - mod;
}
function getVerificationCode2(code1){
var total = 0;
var mod = 0;
var factors = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
var nums = (this.cnpj.substr(0,12)+code1).split('');
for( var i in nums){
total += nums[i]*factors[i];
}
mod = total%11;
return ( mod < 2) ? 0 : 11 - mod;
}
this.cnpj = cnpj.replace(/[^0-9]/g, '');
this.verificationCode1;
this.verificationCode2;
if(this.cnpj.length<14)
throw 'CNPJ é muito curto';
this.verificationCode1 = this.cnpj.substr(-2, 1);
this.verificationCode2 = this.cnpj.substr(-1, 1);
var code1 = getVerificationCode1();
var code2 = getVerificationCode2(code1);
return code1==this.verificationCode1 && code2==this.verificationCode2;
}
console.log( CNPJValidator('11.222.333/0001-81') );