isCnpj static method
Implementation
static bool isCnpj(String cnpj) {
// Get only the numbers from the CNPJ
final numbers = cnpj.replaceAll(RegExp(r'[^0-9]'), '');
// Test if the CNPJ has 14 digits
if (numbers.length != 14) {
return false;
}
// Test if all digits of the CNPJ are the same
if (RegExp(r'^(\d)\1*$').hasMatch(numbers)) {
return false;
}
// Divide digits
final digits = numbers.split('').map(int.parse).toList();
// Calculate the first check digit
var calcDv1 = 0;
var j = 0;
for (var i in Iterable<int>.generate(12, (i) => i < 4 ? 5 - i : 13 - i)) {
calcDv1 += digits[j++] * i;
}
calcDv1 %= 11;
final dv1 = calcDv1 < 2 ? 0 : 11 - calcDv1;
// Test the first check digit
if (digits[12] != dv1) {
return false;
}
// Calculate the second check digit
var calcDv2 = 0;
j = 0;
for (var i in Iterable<int>.generate(13, (i) => i < 5 ? 6 - i : 14 - i)) {
calcDv2 += digits[j++] * i;
}
calcDv2 %= 11;
final dv2 = calcDv2 < 2 ? 0 : 11 - calcDv2;
// Test the second check digit
if (digits[13] != dv2) {
return false;
}
return true;
}