-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinn-validator.go
90 lines (71 loc) · 2.11 KB
/
inn-validator.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
package innValidator
import (
"fmt"
"regexp"
"strconv"
)
func IsLegalPersonInnValid(inn string) (isValid bool, err error) {
weights := [9]int{2, 4, 10, 3, 5, 9, 4, 6, 8}
if !regexp.MustCompile("^[0-9]{10}$").MatchString(inn) {
return false, fmt.Errorf("%s is not legal person inn", inn)
}
array, err := intStringToIntArray(inn)
if err != nil {
return false, fmt.Errorf("%s is not legal person inn", inn)
}
var result int
for index, weight := range weights {
result += array[index] * weight
}
checksum := result % 11 % 10
arrayLastElement := array[len(array)-1]
if checksum == arrayLastElement {
return true, err
} else {
return false, fmt.Errorf("%s is not legal person inn", inn)
}
}
func IsPrivatePersonInnValid(inn string) (isValid bool, err error) {
var weights1 = [10]int{7, 2, 4, 10, 3, 5, 9, 4, 6, 8}
var weights2 = [11]int{3, 7, 2, 4, 10, 3, 5, 9, 4, 6, 8}
if !regexp.MustCompile("^[0-9]{12}$").MatchString(inn) {
return false, fmt.Errorf("%s is not legal person inn", inn)
}
array, err := intStringToIntArray(inn)
if err != nil {
return false, fmt.Errorf("%s is not legal person inn", inn)
}
var result int
for index, weight := range weights1 {
result += array[index] * weight
}
checksum := result % 11 % 10
if checksum != array[10] {
return false, fmt.Errorf("%s is not legal person inn", inn)
}
result = 0
for index, weight := range weights2 {
result += array[index] * weight
}
checksum = result % 11 % 10
if checksum != array[11] {
return false, fmt.Errorf("%s is not legal person inn", inn)
}
return true, err
}
func intStringToIntArray(inputString string) (array []int, err error) {
if inputString == "" {
return []int{}, fmt.Errorf("%s is empty", inputString)
}
for _, value := range inputString {
char := string(value)
// strconv.Atoi return integer and nil error
// if all chars in string is integer
digit, err := strconv.Atoi(char)
if err != nil {
return []int{}, fmt.Errorf("%s in %s is not int", char, inputString)
}
array = append(array, digit)
}
return
}