forked from NdoleStudio/httpsms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidator.go
More file actions
96 lines (77 loc) · 2.52 KB
/
validator.go
File metadata and controls
96 lines (77 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package validators
import (
"context"
"fmt"
"net/url"
"github.com/NdoleStudio/httpsms/pkg/events"
"github.com/nyaruka/phonenumbers"
"github.com/thedevsaddam/govalidator"
)
type validator struct{}
const (
phoneNumberRule = "phoneNumber"
multiplePhoneNumberRule = "multiplePhoneNumber"
webhookEventsRule = "webhookEvents"
)
func init() {
// custom rules to take fixed length word.
// e.g: max_word:5 will throw error if the field contains more than 5 words
govalidator.AddCustomRule(phoneNumberRule, func(field string, rule string, message string, value interface{}) error {
phoneNumber, ok := value.(string)
if !ok {
return fmt.Errorf("the %s field must be a valid E.164 phone number: https://en.wikipedia.org/wiki/E.164", field)
}
_, err := phonenumbers.Parse(phoneNumber, phonenumbers.UNKNOWN_REGION)
if err != nil {
return fmt.Errorf("the %s field must be a valid E.164 phone number: https://en.wikipedia.org/wiki/E.164", field)
}
return nil
})
govalidator.AddCustomRule(multiplePhoneNumberRule, func(field string, rule string, message string, value interface{}) error {
phoneNumbers, ok := value.([]string)
if !ok {
return fmt.Errorf("the %s field must be an array of a valid E.164 phone number: https://en.wikipedia.org/wiki/E.164", field)
}
for index, number := range phoneNumbers {
_, err := phonenumbers.Parse(number, phonenumbers.UNKNOWN_REGION)
if err != nil {
return fmt.Errorf("the %s value in index [%d] must be a valid E.164 phone number: https://en.wikipedia.org/wiki/E.164", field, index)
}
}
return nil
})
govalidator.AddCustomRule(webhookEventsRule, func(field string, rule string, message string, value interface{}) error {
input, ok := value.([]string)
if !ok {
return fmt.Errorf("the %s field must be a string array", field)
}
if len(input) == 0 {
return fmt.Errorf("the %s field is an empty array", field)
}
validEvents := map[string]bool{
events.EventTypeMessagePhoneReceived: true,
}
for _, event := range input {
if _, ok := validEvents[event]; !ok {
return fmt.Errorf("the %s field has an invalid event with name [%s]", field, event)
}
}
return nil
})
}
// ValidateUUID that the payload is a UUID
func (validator *validator) ValidateUUID(_ context.Context, ID string, name string) url.Values {
request := map[string]string{
name: ID,
}
v := govalidator.New(govalidator.Options{
Data: &request,
Rules: govalidator.MapData{
name: []string{
"required",
"uuid",
},
},
})
return v.ValidateStruct()
}