-
Notifications
You must be signed in to change notification settings - Fork 0
/
normalize.go
68 lines (60 loc) · 1.55 KB
/
normalize.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
package normalize_phone
import (
"errors"
"fmt"
"strings"
)
var ErrIncorrectPhone = errors.New("incorrect phone")
// NormalizePhone changes phone string to international format without spaces or other symbols
func NormalizePhone(countryCode, phoneNumber string) (string, error) {
if phoneNumber == "" {
return phoneNumber, nil
}
// remove all non-digits
phoneNumber = strings.Map(
func(c rune) rune {
if (c >= '0' && c <= '9') || c == '+' {
return c
}
return -1
},
phoneNumber,
)
// international number
if len(phoneNumber) > 0 && phoneNumber[0] == '+' {
phoneNumber = phoneNumber[1:]
for _, f := range countryPhoneFormat {
if strings.HasPrefix(phoneNumber, f.Prefix) {
for _, l := range f.Lengths {
if len(phoneNumber) == l+len(f.Prefix) {
return "+" + phoneNumber, nil
}
}
}
}
return "", ErrIncorrectPhone
}
// country-specific checks
f, ok := countryPhoneFormat[countryCode]
if !ok {
return "", fmt.Errorf("unknown country code '%s'", countryCode)
}
prefixMatches := strings.HasPrefix(phoneNumber, f.Prefix)
for _, l := range f.Lengths {
// with prefix, but without plus
if prefixMatches && len(phoneNumber) == l+len(f.Prefix) {
return "+" + phoneNumber, nil
}
// without prefix
if len(phoneNumber) == l {
return "+" + f.Prefix + phoneNumber, nil
}
// with trunk prefix
for _, t := range f.TrunkPrefixes {
if strings.HasPrefix(phoneNumber, t) && len(phoneNumber) == l+len(t) {
return "+" + f.Prefix + phoneNumber[len(t):], nil
}
}
}
return "", ErrIncorrectPhone
}