-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidarCpf.js
More file actions
49 lines (40 loc) · 1.27 KB
/
validarCpf.js
File metadata and controls
49 lines (40 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
function ValidaCPF (cpfEnviado) {
Object.defineProperty(this, 'cpflimpo', {
enumerable: true,
get: function() {
return cpfEnviado.replace(/\D+/g, '');
}
});
}
ValidaCPF.prototype.valida = function () {
if(typeof this.cpflimpo === 'undefined') return false;
if(this.cpflimpo.length !== 11) return false;
if(this.isSequencia()) return false;
const cpfParcial = this.cpflimpo.slice(0, -2);
const Digito1 = this.CriaDigito(cpfParcial);
const Digito2 = this.CriaDigito(cpfParcial + Digito1);
const novoCpf = cpfParcial + Digito1 + Digito2;
return novoCpf === this.cpflimpo;
};
ValidaCPF.prototype.CriaDigito = function(cpfParcial) {
const cpfArray = Array.from(cpfParcial);
let regressivo = cpfArray.length + 1;
const total = cpfArray.reduce((ac, val) => {
ac += (regressivo * Number(val));
regressivo--;
return ac
}, 0)
const digito = 11 - (total % 11)
return digito > 9 ? '0' : String(digito);
};
ValidaCPF.prototype.isSequencia = function () {
const sequencia = this.cpflimpo[0].repeat(this.cpflimpo.length);
return sequencia === this.cpflimpo;
};
const cpf = new ValidaCPF('070.987.720-03');
if (cpf.valida()) {
console.log('cpf válido')
} else {
console.log('cpf inválido')
}
//