-
Notifications
You must be signed in to change notification settings - Fork 9
/
cpf_cnpj.go
130 lines (119 loc) · 2.37 KB
/
cpf_cnpj.go
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package goutils
import (
"errors"
"strconv"
"strings"
)
/*
ValidationCPF o antigo nome era: ValidaCPF
*/
func ValidationCPF(cpf string) error {
cpf = strings.Replace(cpf, ".", "", -1)
cpf = strings.Replace(cpf, "-", "", -1)
if len(cpf) != 11 {
return errors.New("CPF inválido")
}
var eq bool
var dig string
for _, val := range cpf {
if len(dig) == 0 {
dig = string(val)
}
if string(val) == dig {
eq = true
continue
}
eq = false
break
}
if eq {
return errors.New("CPF inválido")
}
i := 10
sum := 0
for index := 0; index < len(cpf)-2; index++ {
pos, _ := strconv.Atoi(string(cpf[index]))
sum += pos * i
i--
}
prod := sum * 10
mod := prod % 11
if mod == 10 {
mod = 0
}
digit1, _ := strconv.Atoi(string(cpf[9]))
if mod != digit1 {
return errors.New("CPF inválido")
}
i = 11
sum = 0
for index := 0; index < len(cpf)-1; index++ {
pos, _ := strconv.Atoi(string(cpf[index]))
sum += pos * i
i--
}
prod = sum * 10
mod = prod % 11
if mod == 10 {
mod = 0
}
digit2, _ := strconv.Atoi(string(cpf[10]))
if mod != digit2 {
return errors.New("CPF inválido")
}
return nil
}
/*
ValidationCNPJ o antigo nome era: ValidaCNPJ
*/
func ValidationCNPJ(cnpj string) error {
cnpj = strings.Replace(cnpj, ".", "", -1)
cnpj = strings.Replace(cnpj, "-", "", -1)
cnpj = strings.Replace(cnpj, "/", "", -1)
if len(cnpj) != 14 {
return errors.New("CNPJ inválido")
}
algs := []int{5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2}
var algProdCpfDig1 = make([]int, 12, 12)
for key, val := range algs {
intParsed, _ := strconv.Atoi(string(cnpj[key]))
sumTmp := val * intParsed
algProdCpfDig1[key] = sumTmp
}
sum := 0
for _, val := range algProdCpfDig1 {
sum += val
}
digit1 := sum % 11
if digit1 < 2 {
digit1 = 0
} else {
digit1 = 11 - digit1
}
char12, _ := strconv.Atoi(string(cnpj[12]))
if char12 != digit1 {
return errors.New("CNPJ inválido")
}
algs = append([]int{6}, algs...)
var algProdCpfDig2 = make([]int, 13, 13)
for key, val := range algs {
intParsed, _ := strconv.Atoi(string(cnpj[key]))
sumTmp := val * intParsed
algProdCpfDig2[key] = sumTmp
}
sum = 0
for _, val := range algProdCpfDig2 {
sum += val
}
digit2 := sum % 11
if digit2 < 2 {
digit2 = 0
} else {
digit2 = 11 - digit2
}
char13, _ := strconv.Atoi(string(cnpj[13]))
if char13 != digit2 {
return errors.New("CNPJ inválido")
}
return nil
}