1
+ class ValidacaoCpf {
2
+ constructor ( cpf ) {
3
+ this . cpf = cpf ;
4
+ this . numeroLimpo ;
5
+ this . numeroLimpoArray = [ ] ;
6
+ this . verdadeiro ;
7
+ }
8
+
9
+ limparCPF ( ) {
10
+ this . numeroLimpo = this . cpf ;
11
+ for ( let i = 0 ; i < this . numeroLimpo . length ; i ++ ) {
12
+ if ( this . numeroLimpo [ i ] !== '.' && this . numeroLimpo [ i ] !== '-' ) {
13
+ this . numeroLimpoArray . push ( this . numeroLimpo [ i ] )
14
+ } else {
15
+ continue
16
+ }
17
+ }
18
+ return this . numeroLimpoArray
19
+ }
20
+
21
+ esquecerCPF ( ) {
22
+ this . numeroLimpoArray = [ ] ;
23
+ }
24
+
25
+ converterCPFEmNumero ( ) {
26
+ this . numeroLimpoArray = this . limparCPF ( ) . map ( ( value ) => parseInt ( value ) )
27
+ return this . numeroLimpoArray
28
+ }
29
+
30
+ somaDigitoUm ( ) {
31
+ let acum = 10 ;
32
+ const somaPrimeiro = this . converterCPFEmNumero ( ) . reduce ( ( acumF , valor , indice , array ) => {
33
+ if ( indice < array . length - 2 ) {
34
+ acumF += valor * acum
35
+ acum --
36
+ }
37
+ return acumF
38
+ } , 0 )
39
+ let primeiroNumero = 11 - ( somaPrimeiro % 11 ) ;
40
+ if ( primeiroNumero > 9 ) primeiroNumero = 0 ;
41
+ return primeiroNumero
42
+ }
43
+
44
+ somaDigitoDois ( ) {
45
+ let acum = 11 ;
46
+ const somaSegundo = this . numeroLimpoArray . reduce ( ( acumF , valor , indice , array ) => {
47
+ if ( indice < array . length - 1 ) {
48
+ acumF += valor * acum
49
+ acum --
50
+ }
51
+ return acumF
52
+ } , 0 )
53
+ let segundoNumero = 11 - ( somaSegundo % 11 ) ;
54
+ if ( segundoNumero > 9 ) segundoNumero = 0 ;
55
+ return segundoNumero
56
+ }
57
+
58
+ verificarSequencia ( ) {
59
+ const possivelSequencia = this . numeroLimpoArray . filter ( ( valor ) => valor === this . numeroLimpoArray [ 0 ] )
60
+ return ! ( possivelSequencia . length === 11 )
61
+ }
62
+
63
+ verificacaoUm ( ) {
64
+ return this . somaDigitoUm ( ) === this . numeroLimpoArray [ 9 ] ;
65
+ }
66
+
67
+ verificacaoDois ( ) {
68
+ return this . somaDigitoDois ( ) === this . numeroLimpoArray [ 10 ] ;
69
+ }
70
+
71
+ verificaçãoGeral ( ) {
72
+ if ( this . verificacaoUm ( ) && this . verificacaoDois ( ) && this . verificarSequencia ( ) ) return 'cpf valido' ;
73
+ else return 'cpf invalido'
74
+ }
75
+ }
76
+
77
+
78
+
79
+
80
+ const cpf1 = new ValidacaoCpf ( '031.205.580-36' )
81
+ console . log ( cpf1 . limparCPF ( ) )
82
+ console . log ( cpf1 . verificaçãoGeral ( ) )
83
+
84
+ document . addEventListener ( 'click' , function ( event ) {
85
+ const ev = event . target ;
86
+ const input = document . querySelector ( '.verification-input input' )
87
+ if ( ev . classList . contains ( 'verification-button' ) ) {
88
+ const cpfDOM = new ValidacaoCpf ( input . value ) ;
89
+ alert ( cpfDOM . verificaçãoGeral ( ) )
90
+ }
91
+ } )
0 commit comments