This repository has been archived by the owner on Mar 18, 2024. It is now read-only.
/
validate.go
236 lines (213 loc) · 6.37 KB
/
validate.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
package rpcutil
import (
"errors"
"fmt"
"reflect"
"regexp"
"net/mail"
"strconv"
"strings"
"time"
"gopkg.in/validator.v2"
)
var vRegexes = map[string]*regexp.Regexp{}
// RegisterRegex registers a regex with a given name, so it can be used as an
// argument to various custom validators installed by this package
func RegisterRegex(name, regex string) {
vRegexes[name] = regexp.MustCompile(regex)
}
// InstallCustomValidators will set up our set of custom validators for the
// gopkg.in/validator.v2 package. You can see available validators which are
// installed by looking for the Validate* functions in this package
func InstallCustomValidators() {
validator.SetValidationFunc("preRegex", ValidatePreRegex)
validator.SetValidationFunc("arrMap", ValidateArrMap)
validator.SetValidationFunc("lens", ValidateLens)
validator.SetValidationFunc("email", ValidateEmail)
validator.SetValidationFunc("futureTime", ValidateFutureTime)
}
// ValidatePreRegex will run a regex named by regexName on a string. This is
// registered as the "preRegex" validator, and can be used like
// `validate:"preRegex=regexName"` (see gopkg.in/validator.v2) in conjunction
// with RegisterRegex
//
// When validating this will allow through an empty string
func ValidatePreRegex(v interface{}, regexName string) error {
r, ok := vRegexes[regexName]
if !ok {
panic(fmt.Sprintf("unknown regex: %q", regexName))
}
vs, ok := v.(string)
if !ok {
return validator.ErrUnsupported
}
// We allow blank strings no matter what, if a blank string is not wanted to
// be allowed then the "nonzero" validator should be added
if vs == "" {
return nil
}
if !r.Match([]byte(vs)) {
return errors.New("badly formatted")
}
return nil
}
// ValidateArrMap maps over an array and validates each element in it using the
// passed in tag. For example
//
// validator:"min=1,arrMap=min=1,arrMap=max=5,arrMap=regexp=[A-Z]+"
func ValidateArrMap(v interface{}, param string) error {
vv := reflect.ValueOf(v)
if vv.Kind() == reflect.Ptr {
vv = vv.Elem()
}
if k := vv.Kind(); k != reflect.Slice && k != reflect.Array {
return fmt.Errorf("non-array type: %s", k)
}
for i := 0; i < vv.Len(); i++ {
vi := vv.Index(i).Interface()
if err := validator.Valid(vi, param); err != nil {
return fmt.Errorf("invalid index %d: %s", i, err)
}
}
return nil
}
// equalsInts takes an int64 and makes sure it finds that value in a array
// of string int64's otherwise it returns false. It returns an error if an
// unparseable string is sent
func equalsInts(a int64, bs []string) (bool, error) {
for _, v := range bs {
b, err := strconv.ParseInt(v, 0, 64)
if err != nil {
return false, validator.ErrBadParameter
}
if b == a {
return true, nil
}
}
return false, nil
}
// equalsUints takes an uint64 and makes sure it finds that value in a array
// of string uint64's otherwise it returns false. It returns an error if an
// unparseable string is sent
func equalsUints(a uint64, bs []string) (bool, error) {
for _, v := range bs {
b, err := strconv.ParseUint(v, 0, 64)
if err != nil {
return false, validator.ErrBadParameter
}
if b == a {
return true, nil
}
}
return false, nil
}
// equalsFloats takes a float64 and makes sure it finds that value in a array
// of string float64's otherwise it returns false. It returns an error if an
// unparseable string is sent
func equalsFloats(a float64, bs []string) (bool, error) {
for _, v := range bs {
b, err := strconv.ParseFloat(v, 64)
if err != nil {
return false, validator.ErrBadParameter
}
if b == a {
return true, nil
}
}
return false, nil
}
// ValidateLens validates the length of a string or slice and errors if the
// length is not equal to a passed in option. For numbers it verifies that the
// number equals one of the passed values. For example
//
// validator:"lens=2|0"
func ValidateLens(v interface{}, param string) error {
p := strings.Split(param, "|")
if len(p) == 0 {
return nil
}
st := reflect.ValueOf(v)
switch st.Kind() {
case reflect.String:
if valid, err := equalsInts(int64(len(st.String())), p); !valid {
if err == nil {
err = validator.ErrLen
}
return err
}
case reflect.Slice, reflect.Map, reflect.Array:
if valid, err := equalsInts(int64(st.Len()), p); !valid {
if err == nil {
err = validator.ErrLen
}
return err
}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if valid, err := equalsInts(st.Int(), p); !valid {
if err == nil {
err = validator.ErrLen
}
return err
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
if valid, err := equalsUints(st.Uint(), p); !valid {
if err == nil {
err = validator.ErrLen
}
return err
}
case reflect.Float32, reflect.Float64:
if valid, err := equalsFloats(st.Float(), p); !valid {
if err == nil {
err = validator.ErrLen
}
return err
}
default:
return validator.ErrUnsupported
}
return nil
}
// ValidateEmail validates a string as an email address as defined by RFC 5322
// Behind the scenes it just uses ParseAddress in the src/net/mail package
func ValidateEmail(v interface{}, _ string) error {
email, ok := v.(string)
if !ok {
return validator.ErrUnsupported
}
// We allow blank strings no matter what, if a blank string is not wanted to
// be allowed then the "nonzero" validator should be added
if email == "" {
return nil
}
a, err := mail.ParseAddress(email)
if err == nil && a.Address != email {
err = fmt.Errorf("email interpreted as \"%s\" but was sent \"%s\"", a.Address, email)
}
return err
}
// ValidateFutureTime validates that the time is > than now + (duration value)
// The default value is -15m (-15 minutes). It is not exactly 0 hours
// to prevent client time differences causing user frustration. Do not rely on
// the default value being -15m as it might change slightly in the future. If
// you want 0 hours just set "0".
// For example: futureTime=-4h validates that the time is > now - 4 hours
func ValidateFutureTime(v interface{}, s string) error {
var err error
offset := -15 * time.Minute
if s != "" {
offset, err = time.ParseDuration(s)
if err != nil {
return validator.ErrBadParameter
}
}
t, ok := v.(interface {
After(time.Time) bool
})
if !ok {
return validator.ErrUnsupported
} else if !t.After(time.Now().Add(offset)) {
return fmt.Errorf("time is not greater than now %s", s)
}
return nil
}