github.com/ronaksoft/rony@v0.16.26-0.20230807065236-1743dbfe6959/tools/phoneutil/phone.go (about) 1 package phoneutil 2 3 import ( 4 "fmt" 5 "regexp" 6 "strings" 7 8 "github.com/nyaruka/phonenumbers" 9 ) 10 11 /* 12 Creation Time: 2019 - Oct - 13 13 Created by: (ehsan) 14 Maintainers: 15 1. Ehsan N. Moosa (E2) 16 Auditor: Ehsan N. Moosa (E2) 17 Copyright Ronak Software Group 2020 18 */ 19 20 var ( 21 RegExPhone *regexp.Regexp 22 ) 23 24 func init() { 25 exp1, err := regexp.Compile(`^[+\d]\d*$`) 26 if err != nil { 27 panic(err) 28 } 29 RegExPhone = exp1 30 } 31 32 func SanitizePhone(phoneNumber string, defaultRegion string) (string, error) { 33 if defaultRegion == "" { 34 defaultRegion = GetCountryCode(phoneNumber) 35 } 36 phoneNumber = strings.TrimLeft(phoneNumber, "0+ ") 37 if !RegExPhone.MatchString(phoneNumber) { 38 return "", fmt.Errorf("did not match phone number regex") 39 } 40 phone, err := phonenumbers.Parse(phoneNumber, defaultRegion) 41 if err != nil { 42 phoneNumber = fmt.Sprintf("+%s", phoneNumber) 43 phone, err = phonenumbers.Parse(phoneNumber, defaultRegion) 44 if err != nil { 45 return "", err 46 } 47 } 48 49 if !phonenumbers.IsValidNumberForRegion(phone, phonenumbers.GetRegionCodeForNumber(phone)) { 50 return "", fmt.Errorf("not valid for region") 51 } 52 53 return fmt.Sprintf("%d%d", phone.GetCountryCode(), phone.GetNationalNumber()), nil 54 } 55 56 func GetCountryCode(phone string) string { 57 phone = fmt.Sprintf("+%s", strings.TrimLeft(phone, "+")) 58 ph, err := phonenumbers.Parse(phone, "") 59 if err != nil { 60 return "" 61 } 62 63 return phonenumbers.GetRegionCodeForNumber(ph) 64 }