Created
January 6, 2014 17:52
-
-
Save zipmegabyte/8286613 to your computer and use it in GitHub Desktop.
A simple js validator for CPF /CNPJ
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
function validateCpfCnpj(cpfCnpj) { | |
'use strict'; | |
var arr; | |
function buildDigit(arr) { | |
var isCpf = arr.length < 11, | |
digit = arr.map(function (val, idx) {return val * ((!isCpf ? idx % 8 : idx) + 2)}).reduce(function (total, current) {return total + current}) % 11; | |
if (digit < 2 && isCpf) return 0; | |
return 11 - digit; | |
}; | |
cpfCnpj = cpfCnpj.replace(/\D/g, ''); | |
if ([11, 14].indexOf(cpfCnpj.length) < 0) return false; | |
arr = cpfCnpj.split('').reverse().slice(2); | |
arr.unshift(buildDigit(arr)); | |
arr.unshift(buildDigit(arr)); | |
return cpfCnpj === arr.reverse().join(''); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I tried it out for the following use case:
CNPJ8 + BranchNumber + XX
While the idea was to find XX using the script above.
In some 65% cases it works. For remaining 33% it does not return any number.
Example CNPJ that it claims to be wrong but that are in fact possible:
12481307000130