File tree 2 files changed +14
-1
lines changed
2 files changed +14
-1
lines changed Original file line number Diff line number Diff line change @@ -2,6 +2,7 @@ package i18n
2
2
3
3
import (
4
4
"database/sql/driver"
5
+ "regexp"
5
6
6
7
"github.com/nyaruka/null/v2"
7
8
"github.com/nyaruka/phonenumbers"
@@ -13,13 +14,23 @@ type Country string
13
14
// NilCountry represents our nil, or unknown country
14
15
var NilCountry = Country ("" )
15
16
17
+ var countryPattern = regexp .MustCompile (`^[A-Z][A-Z]$` )
18
+
16
19
// DeriveCountryFromTel attempts to derive a country code (e.g. RW) from a phone number
17
20
func DeriveCountryFromTel (number string ) Country {
18
21
parsed , err := phonenumbers .Parse (number , "" )
19
22
if err != nil {
20
23
return ""
21
24
}
22
- return Country (phonenumbers .GetRegionCodeForNumber (parsed ))
25
+
26
+ region := phonenumbers .GetRegionCodeForNumber (parsed )
27
+
28
+ // check this is an actual country code and not a special "region" like 001
29
+ if countryPattern .MatchString (region ) {
30
+ return Country (region )
31
+ }
32
+
33
+ return NilCountry
23
34
}
24
35
25
36
// Place nicely with NULLs if persisting to a database or JSON
Original file line number Diff line number Diff line change @@ -10,6 +10,8 @@ import (
10
10
func TestDeriveCountryFromTel (t * testing.T ) {
11
11
assert .Equal (t , i18n .Country ("RW" ), i18n .DeriveCountryFromTel ("+250788383383" ))
12
12
assert .Equal (t , i18n .Country ("EC" ), i18n .DeriveCountryFromTel ("+593979000000" ))
13
+
14
+ assert .Equal (t , i18n .NilCountry , i18n .DeriveCountryFromTel ("+80000000000" )) // ignore 001
13
15
assert .Equal (t , i18n .NilCountry , i18n .DeriveCountryFromTel ("1234" ))
14
16
15
17
v , err := i18n .Country ("RW" ).Value ()
You can’t perform that action at this time.
0 commit comments