-
Notifications
You must be signed in to change notification settings - Fork 5
/
cpf.go
84 lines (63 loc) · 1.52 KB
/
cpf.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
// Package cpfcnpj provides functions for validate CPF and CNPJ, the Brazilian taxpayer registry identification document
package cpfcnpj
import (
"fmt"
"regexp"
"strconv"
)
var (
cpfFirstDigitTable = []int{10, 9, 8, 7, 6, 5, 4, 3, 2}
cpfSecondDigitTable = []int{11, 10, 9, 8, 7, 6, 5, 4, 3, 2}
)
const (
// CPFFormatPattern is the pattern for string replacement
// with Regex
CPFFormatPattern string = `([\d]{3})([\d]{3})([\d]{3})([\d]{2})`
)
// CPF type definition
type CPF string
// NewCPF is a helper function to convert and clean a new CPF
// from a string
func NewCPF(s string) CPF {
return CPF(Clean(s))
}
// IsValid returns if CPF is a valid CPF document
func (c *CPF) IsValid() bool {
return ValidateCPF(string(*c))
}
// String returns a formatted CPF document
// 000.000.000-00
func (c *CPF) String() string {
str := string(*c)
if !c.IsValid() {
return str
}
expr, err := regexp.Compile(CPFFormatPattern)
if err != nil {
return str
}
return expr.ReplaceAllString(str, "$1.$2.$3-$4")
}
// ValidateCPF validates a CPF document
// You should use without punctuation
func ValidateCPF(cpf string) bool {
if len(cpf) != 11 {
return false
}
firstPart := cpf[0:9]
sum := sumDigit(firstPart, cpfFirstDigitTable)
r1 := sum % 11
d1 := 0
if r1 >= 2 {
d1 = 11 - r1
}
secondPart := firstPart + strconv.Itoa(d1)
dsum := sumDigit(secondPart, cpfSecondDigitTable)
r2 := dsum % 11
d2 := 0
if r2 >= 2 {
d2 = 11 - r2
}
finalPart := fmt.Sprintf("%s%d%d", firstPart, d1, d2)
return finalPart == cpf
}