Skip to content

Commit 96ce48d

Browse files
committed
i18n.DeriveCountryFromTel shouldn't return non-country codes like '001'
1 parent 0866e1d commit 96ce48d

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

i18n/country.go

+12-1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package i18n
22

33
import (
44
"database/sql/driver"
5+
"regexp"
56

67
"github.com/nyaruka/null/v2"
78
"github.com/nyaruka/phonenumbers"
@@ -13,13 +14,23 @@ type Country string
1314
// NilCountry represents our nil, or unknown country
1415
var NilCountry = Country("")
1516

17+
var countryPattern = regexp.MustCompile(`^[A-Z][A-Z]$`)
18+
1619
// DeriveCountryFromTel attempts to derive a country code (e.g. RW) from a phone number
1720
func DeriveCountryFromTel(number string) Country {
1821
parsed, err := phonenumbers.Parse(number, "")
1922
if err != nil {
2023
return ""
2124
}
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
2334
}
2435

2536
// Place nicely with NULLs if persisting to a database or JSON

i18n/country_test.go

+2
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ import (
1010
func TestDeriveCountryFromTel(t *testing.T) {
1111
assert.Equal(t, i18n.Country("RW"), i18n.DeriveCountryFromTel("+250788383383"))
1212
assert.Equal(t, i18n.Country("EC"), i18n.DeriveCountryFromTel("+593979000000"))
13+
14+
assert.Equal(t, i18n.NilCountry, i18n.DeriveCountryFromTel("+80000000000")) // ignore 001
1315
assert.Equal(t, i18n.NilCountry, i18n.DeriveCountryFromTel("1234"))
1416

1517
v, err := i18n.Country("RW").Value()

0 commit comments

Comments
 (0)