common/phone/phone.go

42 lines
1.1 KiB
Go
Raw Normal View History

2025-01-12 09:17:29 +01:00
package phone
import (
2025-01-12 09:27:04 +01:00
"errors"
2025-01-12 09:17:29 +01:00
"regexp"
2025-01-12 09:27:04 +01:00
"strings"
2025-01-12 09:17:29 +01:00
)
// Define the regex patterns as constants
const (
2025-01-21 16:59:44 +01:00
// TODO: This should rather use a phone package to determine whether valid phone number for any region.
phoneRegex = `^(?:\+254|254|0)?((?:7[0-9]{8})|(?:1[01][0-9]{7}))$`
2025-01-12 09:17:29 +01:00
)
// IsValidPhoneNumber checks if the given number is a valid phone number
func IsValidPhoneNumber(phonenumber string) bool {
match, _ := regexp.MatchString(phoneRegex, phonenumber)
return match
}
2025-01-12 09:27:04 +01:00
// FormatPhoneNumber formats a Kenyan phone number to "+254xxxxxxxx".
func FormatPhoneNumber(phone string) (string, error) {
if !IsValidPhoneNumber(phone) {
2025-01-21 16:59:44 +01:00
return "", errors.New("invalid phone number")
2025-01-12 09:27:04 +01:00
}
// Remove any leading "+" and spaces
phone = strings.TrimPrefix(phone, "+")
phone = strings.ReplaceAll(phone, " ", "")
// Replace leading "0" with "254" if present
if strings.HasPrefix(phone, "0") {
2025-01-21 16:59:44 +01:00
phone = "254" + phone[1:]
2025-01-12 09:27:04 +01:00
}
// Add "+" if not already present
if !strings.HasPrefix(phone, "254") {
2025-01-21 16:59:44 +01:00
return "", errors.New("unexpected format")
2025-01-12 09:27:04 +01:00
}
return "+" + phone, nil
}