-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidandoCpf.js
52 lines (42 loc) · 1.37 KB
/
validandoCpf.js
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
50
51
// Validando CPF com js
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('705.484.450-52');
// console.log(cpf.valida());
// cpf.valida();
if (cpf.valida()){
console.log('CPF válido');
} else {
console.log('CPF inválido');
};