-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstring.go
105 lines (84 loc) · 2.13 KB
/
string.go
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
97
98
99
100
101
102
103
104
105
package validator
import (
"errors"
"fmt"
"net/mail"
"strconv"
"unicode/utf8"
"github.com/nyaruka/phonenumbers"
)
type StringValidators []stringValidator
type stringValidator interface {
Validate(value string) error
}
type StringMaxValidator struct {
Max int
}
func (v StringMaxValidator) Validate(value string) error {
if utf8.RuneCountInString(value) > v.Max {
return fmt.Errorf("value length must not be greater than %v", v.Max)
}
return nil
}
type StringMinValidator struct {
Min int
}
func (v StringMinValidator) Validate(value string) error {
if utf8.RuneCountInString(value) < v.Min {
return fmt.Errorf("value length must not be greater than %v", v.Min)
}
return nil
}
type StringEmailValidator struct{}
func (v StringEmailValidator) Validate(value string) error {
if _, err := mail.ParseAddress(value); err != nil {
return fmt.Errorf("value is not an email")
}
return nil
}
type StringPhoneValidator struct{}
func (v StringPhoneValidator) Validate(value string) error {
if _, err := phonenumbers.Parse(value, ""); err != nil {
return fmt.Errorf("value is not an international phone number")
}
return nil
}
func ValidateMapString(name string, value map[string]any, rules StringValidators) (string, error) {
rawValue, ok := value[name]
if !ok {
return "", fmt.Errorf("missing key \"%v\"", name)
}
return ValidateString(rawValue, rules)
}
func ValidateMapStringOrNil(
name string,
value map[string]any,
rules StringValidators,
) (*string, error) {
rawValue, ok := value[name]
if !ok {
return nil, nil
}
val, err := ValidateString(rawValue, rules)
return &val, err
}
func ValidateString(value any, rules StringValidators) (string, error) {
stringValue, stringOk := value.(string)
intValue, intOk := value.(int)
floatValue, floatOk := value.(float64)
if !stringOk && !intOk && !floatOk {
return "", errors.New("value is not a string")
}
if intOk {
stringValue = strconv.Itoa(intValue)
}
if floatOk {
stringValue = strconv.FormatFloat(floatValue, 'f', -1, 64)
}
for _, rule := range rules {
if err := rule.Validate(stringValue); err != nil {
return "", err
}
}
return stringValue, nil
}