-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathvalidator_phone.go
More file actions
93 lines (85 loc) · 2.27 KB
/
Copy pathvalidator_phone.go
File metadata and controls
93 lines (85 loc) · 2.27 KB
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
91
92
93
package validator
import (
"github.com/nyaruka/phonenumbers"
)
// IsPhoneE164 validates phone number in E.164 format (+[country code][number])
func IsPhoneE164(str string) bool {
if str == "" {
return false
}
// E.164 must start with +
if str[0] != '+' {
return false
}
num, err := phonenumbers.Parse(str, "")
if err != nil {
return false
}
return phonenumbers.IsValidNumber(num)
}
// IsPhone validates phone number for a specific region (ISO 3166-1 alpha-2)
func IsPhone(str string, region string) bool {
if str == "" {
return false
}
num, err := phonenumbers.Parse(str, region)
if err != nil {
return false
}
return phonenumbers.IsValidNumberForRegion(num, region)
}
// IsPhoneValid validates phone number (any format, any region)
func IsPhoneValid(str string) bool {
if str == "" {
return false
}
// Try E.164 first
if str[0] == '+' {
num, err := phonenumbers.Parse(str, "")
if err != nil {
return false
}
return phonenumbers.IsValidNumber(num)
}
// Without country code, we can't validate properly
return false
}
// IsPhoneMobile validates if phone number is a mobile number
func IsPhoneMobile(str string, region string) bool {
if str == "" {
return false
}
num, err := phonenumbers.Parse(str, region)
if err != nil {
return false
}
if !phonenumbers.IsValidNumber(num) {
return false
}
numType := phonenumbers.GetNumberType(num)
return numType == phonenumbers.MOBILE || numType == phonenumbers.FIXED_LINE_OR_MOBILE
}
// FormatPhoneE164 formats phone number to E.164 format
func FormatPhoneE164(str string, region string) (string, error) {
num, err := phonenumbers.Parse(str, region)
if err != nil {
return "", err
}
return phonenumbers.Format(num, phonenumbers.E164), nil
}
// FormatPhoneNational formats phone number to national format
func FormatPhoneNational(str string, region string) (string, error) {
num, err := phonenumbers.Parse(str, region)
if err != nil {
return "", err
}
return phonenumbers.Format(num, phonenumbers.NATIONAL), nil
}
// FormatPhoneInternational formats phone number to international format
func FormatPhoneInternational(str string, region string) (string, error) {
num, err := phonenumbers.Parse(str, region)
if err != nil {
return "", err
}
return phonenumbers.Format(num, phonenumbers.INTERNATIONAL), nil
}