Created
May 27, 2016 19:02
-
-
Save AlbertoMonteiro/1dfde732da264c7948567a0780261887 to your computer and use it in GitHub Desktop.
Validação CPF/CNPJ em Javascript
This file contains hidden or 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
function validaCnpj(cnpj) { | |
var multiplicadores = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]; | |
return isValidCP(cnpj, multiplicadores, 14); | |
} | |
function validaCpf(cpf) { | |
var multiplicadores = [11, 10, 9, 8, 7, 6, 5, 4, 3, 2]; | |
return isValidCP(cpf, multiplicadores, 11); | |
} | |
function isValidCP(code, multipliers, length) { | |
if (code.length !== length) | |
return false; | |
var digits = code.split("").map(function (str) { return +str; }).splice(0, length - 2); | |
var rest = zip([digits, multipliers.slice(1)]).map(function (ar) { return ar[0] * ar[1]; }).reduce(function (a, b) { return a + b }) % 11; | |
digits.push(rest < 2 ? 0 : 11 - rest); | |
rest = zip([digits, multipliers]).map(function (ar) { return ar[0] * [1]; }).reduce(function (a, b) { return a + b }) % 11; | |
rest = rest < 2 ? 0 : 11 - rest; | |
return new RegExp(rest.toString() + "$").test(code); | |
} | |
function zip(arrays) { | |
return arrays[0].map(function (_, i) { | |
return arrays.map(function (array) { return array[i] }); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment