master
Paulo Simão 2021-09-29 21:28:45 -03:00
commit 08eaa08389
5 changed files with 104 additions and 0 deletions

2
.gitignore vendored 100644
View File

@ -0,0 +1,2 @@
.idea
.vscode

22
README.md 100644
View File

@ -0,0 +1,22 @@
# Validators
Package with multiple complex validation entities (only CPF now)
Usage:
```go
package main
import (
"go.digitalcircle.com.br/open/validators/cpf"
"log"
)
func main() {
acpf := "401.852.780-27"
if cpf.Check(acpf) {
log.Printf("CPF OK: %s", cpf.Format(acpf))
}
}
```

54
cpf/lib.go 100644
View File

@ -0,0 +1,54 @@
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--
}
mod1 := (d1 * 10) % 11
d2 := 0
mul = 11
for _, v := range nums[0 : len(nums)-2] {
d2 = d2 + (v * mul)
mul--
}
d2 = d2 + (mod1 * mul)
mod2 := (d2 * 10) % 11
return mod1 == nums[len(nums)-2] && mod2 == nums[len(nums)-1]
}

23
cpf/lib_test.go 100644
View File

@ -0,0 +1,23 @@
package cpf
import (
"log"
"testing"
)
func TestFormat(t *testing.T) {
log.Printf(Format("03794020685"))
}
func TestCheck(t *testing.T) {
for _, v := range []string{
"377.100.400-47",
"377.100.400-46",
"845.846.910-37",
"845.846.910-17",
} {
ret := Check(v)
log.Printf("%s=>%v", v, ret)
}
}

3
go.mod 100644
View File

@ -0,0 +1,3 @@
module go.digitalcircle.com.br/open/validators
go 1.17