Skip to content

Instantly share code, notes, and snippets.

@cristianobecker
Last active April 26, 2016 17:17
Show Gist options
  • Save cristianobecker/1b7dac461903e4724336 to your computer and use it in GitHub Desktop.
Save cristianobecker/1b7dac461903e4724336 to your computer and use it in GitHub Desktop.
Validar CPF por javascript
var CPF = (function () {
var eleven = 11;
function mod(n) {
var t = eleven,
a = n % t;
return (a < 2 ? 0 : t - n % t) + '';
}
return {
digits: function (numbers) {
var first = 0,
second = 0,
result = '';
for (var i = 0, t = 9, n = eleven; i < t; i += 1, n -= 1) {
var j = numbers[i] | 0;
first += (n - 1) * j;
second += n * j;
}
result = mod(first);
second += 2 * result[0] | 0;
result += mod(second);
return result;
},
check: function (cpf) {
var numbers = (cpf + '').replace(/[^0-9]/g, ''),
first = 0,
second = 0;
if (numbers.length === eleven && numbers !== Array(11 + 1).join('0')) {
return numbers.substr(-2) === this.digits(numbers);
}
return false;
},
generate: function (masked) {
var numbers = [],
result = '',
cpf = '';
for (var i = 0, t = 9; i < t; i += 1) {
numbers[i] = ((Math.random() * 9) + 0.5) | 0;
}
result = numbers.join('');
cpf = result + this.digits(result);
if (masked) {
cpf = this.mask(cpf, true);
}
return cpf;
},
mask: function (cpf, skipCheck) {
if ((skipCheck !== false && this.check(cpf)) || skipCheck) {
var numbers = (cpf + '').replace(/[^0-9]/g, ''),
regex = /(\d{3})(\d{3})(\d{3})(\d{2})/.exec(numbers);
return regex[1] + '.' + regex[2] + '.' + regex[3] + '-' + regex[4];
}
return cpf;
}
};
}());
> CPF.generate();
'73865473822'
> CPF.mask('73865473822');
'738.654.738-22'
> CPF.generate(true);
'946.502.934-30'
> CPF.digits('111222333');
'96'
> CPF.check('111.222.333-96');
true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment