2021-09-30 00:28:45 +00:00
|
|
|
package cpf
|
|
|
|
|
|
|
|
import (
|
|
|
|
"strconv"
|
|
|
|
"unicode"
|
|
|
|
)
|
|
|
|
|
|
|
|
//Gets a string and formats is as CPF
|
|
|
|
func Format(s string) string {
|
|
|
|
raw := Strip(s)
|
|
|
|
ret := raw[0:3] + "." + raw[3:6] + "." + raw[6:9] + "-" + raw[9:11]
|
|
|
|
return ret
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
//Removes all non-digit symbols
|
|
|
|
func Strip(s string) string {
|
|
|
|
ret := ""
|
|
|
|
for _, v := range s {
|
|
|
|
if unicode.IsDigit(v) {
|
|
|
|
ret = ret + string(v)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return ret
|
|
|
|
}
|
|
|
|
|
|
|
|
//Checks if verification digit are respected
|
|
|
|
func Check(s string) bool {
|
|
|
|
raw := Strip(s)
|
|
|
|
nums := make([]int, 0)
|
|
|
|
for _, v := range raw {
|
|
|
|
i, _ := strconv.Atoi(string(v))
|
|
|
|
nums = append(nums, i)
|
|
|
|
}
|
|
|
|
|
|
|
|
d1 := 0
|
|
|
|
mul := 10
|
|
|
|
for _, v := range nums[0 : len(nums)-2] {
|
|
|
|
d1 = d1 + (v * mul)
|
|
|
|
mul--
|
|
|
|
}
|
2021-09-30 20:18:47 +00:00
|
|
|
mod1 := (d1) % 11
|
|
|
|
if mod1 < 2 {
|
|
|
|
mod1 = 0
|
|
|
|
} else {
|
|
|
|
mod1 = 11 - mod1
|
|
|
|
}
|
2021-09-30 00:28:45 +00:00
|
|
|
d2 := 0
|
|
|
|
mul = 11
|
|
|
|
for _, v := range nums[0 : len(nums)-2] {
|
|
|
|
d2 = d2 + (v * mul)
|
|
|
|
mul--
|
|
|
|
}
|
|
|
|
d2 = d2 + (mod1 * mul)
|
|
|
|
|
2021-09-30 20:18:47 +00:00
|
|
|
mod2 := (d2) % 11
|
|
|
|
if mod2 < 2 {
|
|
|
|
mod2 = 0
|
|
|
|
} else {
|
|
|
|
mod2 = 11 - mod2
|
|
|
|
}
|
2021-09-30 00:28:45 +00:00
|
|
|
return mod1 == nums[len(nums)-2] && mod2 == nums[len(nums)-1]
|
|
|
|
}
|