Skip to content

Instantly share code, notes, and snippets.

@rbarros
Last active November 18, 2016 00:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rbarros/6798516 to your computer and use it in GitHub Desktop.
Save rbarros/6798516 to your computer and use it in GitHub Desktop.
Validar CPF
// Author: Ramon Barros <contato@ramon-barros.com>
/* jslint devel: true, unparam: true, indent: 4 */
/* global $,document,window,event,url,introJs,XMLHttpRequest,ActiveXObject,onlyNumbers */
function validarCPF(doc) {
'use strict';
var i, cpf = doc.replace(/\D/g, ''), pattern = /^(\d{1})\1{10}$/, sum, mod, digit;
if (cpf.length !== 11) {
return false;
}
if (pattern.test(cpf)) {
return false;
}
sum = 0;
for (i = 0; i < 9; i += 1) {
sum += parseInt(cpf.charAt(i), 10) * (10 - i);
}
mod = sum % 11;
digit = (mod > 1) ? (11 - mod) : 0;
if (parseInt(cpf.charAt(9), 10) !== digit) {
return false;
}
sum = 0;
for (i = 0; i < 10; i += 1) {
sum += parseInt(cpf.charAt(i), 10) * (11 - i);
}
mod = sum % 11;
digit = (mod > 1) ? (11 - mod) : 0;
if (parseInt(cpf.charAt(10), 10) !== digit) {
return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment