Skip to content

Instantly share code, notes, and snippets.

@zipmegabyte
Created January 6, 2014 17:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save zipmegabyte/8286613 to your computer and use it in GitHub Desktop.
Save zipmegabyte/8286613 to your computer and use it in GitHub Desktop.
A simple js validator for CPF /CNPJ
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('');
};
@eliezerWK
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment