Last active
January 7, 2020 20:22
-
-
Save camaleaun/2ec56de03302626f8cf9d5583661cfc0 to your computer and use it in GitHub Desktop.
CPF and CNPJ validators
This file contains 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
String.prototype.pad = function (length) { | |
'use strict'; | |
var s = this; | |
while (s.length < length) { | |
s = '0' + s; | |
} | |
return s; | |
}; | |
String.prototype.numbers = function () { | |
'use strict'; | |
var result = ''; | |
if (this.match(/(\d+)/g)) { | |
result = this.match(/(\d+)/g).join(''); | |
} | |
return result; | |
}; | |
String.prototype.isCPF = function () { | |
'use strict'; | |
// Keep only numbers, inserts leading zeros ensuring correct size. | |
var cpf = this.numbers().pad(11), | |
valid = true, | |
sum, | |
n, | |
i, | |
d; | |
// Ignore false positives when only repeating single number. | |
if (/^(\d)\1+$/.test(cpf)) { | |
return false; | |
} | |
// Interaction for each check digit. | |
for (n = 0; n < 2; n += 1) { | |
sum = 0; | |
// Multiply positions by decreasing 10 and 11 in the second interaction, accumulating the sum. | |
for (i = 10 + n; i > 1; i -= 1) { | |
sum += cpf.substr(Math.abs(i - 10 - n), 1) * i; | |
} | |
// Calculate module 11 for the calculated digit. | |
d = 11 - sum % 11; | |
// Case 10 replaces with 0. | |
d = d <= 9 ? d : 0; | |
// False when not matching calculated digit with check. | |
if (parseInt(cpf.substr(9 + n, 1), 10) !== d) { | |
return false; | |
} | |
} | |
return true; | |
}; | |
String.prototype.isCNPJ = function () { | |
'use strict'; | |
// Keep only numbers, inserts leading zeros ensuring correct size. | |
var cnpj = this.numbers().pad(14), | |
valid = true, | |
sum, | |
i, | |
d; | |
// Ignore false positives when only repeating single number. | |
if (/^(\d)\1+$/.test(cnpj)) { | |
return false; | |
} | |
// Interaction in each group of multipliers. | |
['543298765432', '6543298765432'].forEach(function (f, n) { | |
sum = 0; | |
// Multiplies each factor by its position in the interaction accumulating the sum. | |
for (i = 0; i < f.length; i += 1) { | |
sum += cnpj.substr(i, 1) * f.substr(i, 1); | |
} | |
// Calculate module 11 for the calculated digit. | |
d = 11 - sum % 11; | |
// Case 10 replaces with 0. | |
d = d <= 9 ? d : 0; | |
// False when not matching calculated digit with check. | |
if (parseInt(cnpj.substr(12 + n, 1), 10) !== d) { | |
valid = false; | |
} | |
}); | |
return valid; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment