From 08eaa08389aa09a351d3e1eb9a966a033236c155 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Paulo=20Sima=CC=83o?= Date: Wed, 29 Sep 2021 21:28:45 -0300 Subject: [PATCH] 1st ver --- .gitignore | 2 ++ README.md | 22 ++++++++++++++++++++ cpf/lib.go | 54 +++++++++++++++++++++++++++++++++++++++++++++++++ cpf/lib_test.go | 23 +++++++++++++++++++++ go.mod | 3 +++ 5 files changed, 104 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 cpf/lib.go create mode 100644 cpf/lib_test.go create mode 100644 go.mod diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d48c759 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.idea +.vscode \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..f011391 --- /dev/null +++ b/README.md @@ -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)) + } +} + +``` \ No newline at end of file diff --git a/cpf/lib.go b/cpf/lib.go new file mode 100644 index 0000000..c58828f --- /dev/null +++ b/cpf/lib.go @@ -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] +} diff --git a/cpf/lib_test.go b/cpf/lib_test.go new file mode 100644 index 0000000..aa0b4dc --- /dev/null +++ b/cpf/lib_test.go @@ -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) + } + +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..468be16 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module go.digitalcircle.com.br/open/validators + +go 1.17