-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphone.go
More file actions
72 lines (60 loc) · 2.52 KB
/
Copy pathphone.go
File metadata and controls
72 lines (60 loc) · 2.52 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
package Intouchpay
import (
"errors"
"fmt"
"github.com/samueltuyizere/validate_rw_phone_numbers"
)
// PhoneValidator validates and sanitizes Rwandan phone numbers
type PhoneValidator struct{}
// NewPhoneValidator creates a new PhoneValidator
func NewPhoneValidator() *PhoneValidator {
return &PhoneValidator{}
}
// SanitizePhoneNumber validates and formats a Rwandan phone number
// It returns the number with the "250" country code prefix
func (p *PhoneValidator) SanitizePhoneNumber(phoneNumber string) (string, error) {
// Remove any existing country code prefix to validate the base number
cleanedNumber := phoneNumber
if len(phoneNumber) > 3 && phoneNumber[:3] == "250" {
cleanedNumber = phoneNumber[3:] // Strip prefix to validate
}
// The validation library expects local format with leading "0"
// If the number doesn't start with "0", add it for validation
validationNumber := cleanedNumber
if len(cleanedNumber) > 0 && cleanedNumber[0] != '0' {
validationNumber = "0" + cleanedNumber
}
// Validate the number without country code
isValidMtn := validate_rw_phone_numbers.ValidateMtn(validationNumber)
isValidAirtelTigo := validate_rw_phone_numbers.ValidateAirtelTigo(validationNumber)
if !isValidMtn && !isValidAirtelTigo {
return "", newValidationError("mobilePhone", "invalid phone number format")
}
// Return with country code prefix
newNumber := fmt.Sprintf("25%s", validationNumber)
return newNumber, nil
}
// SanitizePhoneNumber is a package-level function for backward compatibility
// It validates and formats a Rwandan phone number with the "250" country code prefix
func SanitizePhoneNumber(phoneNumber string) (string, error) {
// Remove any existing country code prefix to validate the base number
cleanedNumber := phoneNumber
if len(phoneNumber) > 3 && phoneNumber[:3] == "250" {
cleanedNumber = phoneNumber[3:] // Strip prefix to validate
}
// The validation library expects local format with leading "0"
// If the number doesn't start with "0", add it for validation
validationNumber := cleanedNumber
if len(cleanedNumber) > 0 && cleanedNumber[0] != '0' {
validationNumber = "0" + cleanedNumber
}
// Validate the number without country code
isValidMtn := validate_rw_phone_numbers.ValidateMtn(validationNumber)
isValidAirtelTigo := validate_rw_phone_numbers.ValidateAirtelTigo(validationNumber)
if !isValidMtn && !isValidAirtelTigo {
return "", errors.New("invalid phone number")
}
// Return with country code prefix
newNumber := fmt.Sprintf("25%s", validationNumber)
return newNumber, nil
}