-
Notifications
You must be signed in to change notification settings - Fork 1
/
rules.go
459 lines (432 loc) · 11.3 KB
/
rules.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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
package check
import (
"database/sql"
"mime/multipart"
"net/url"
"reflect"
"regexp"
"strconv"
"strings"
"github.com/gowww/i18n"
)
var (
reEmail = regexp.MustCompile(`^[^@]+@[^@]+\.[^@]{2,63}$`)
rePhone = regexp.MustCompile(`^\+?(\d|\(|\)|\.|\s){9,20}$`)
)
// A Rule is a checking function to be used inside a Checker.
// It receives the errors map to add encountered errors, the whole form for relative checks, and the specific key to check.
type Rule func(errs Errors, form *multipart.Form, key string)
// Alpha rule checks that value contains alpha characters only.
func Alpha(errs Errors, form *multipart.Form, key string) {
if form == nil && form.Value == nil {
return
}
for _, v := range form.Value[key] {
for i := 0; i < len(v); i++ {
if v[i] < 65 || v[i] > 90 && v[i] < 97 || v[i] > 122 {
errs.Add(key, &Error{Error: ErrNotAlpha})
return
}
}
}
}
// Alphanumeric rule checks that value contains alphaumeric characters only.
func Alphanumeric(errs Errors, form *multipart.Form, key string) {
if form == nil && form.Value == nil {
return
}
for _, v := range form.Value[key] {
for i := 0; i < len(v); i++ {
if v[i] < 48 || v[i] > 57 && v[i] < 65 || v[i] > 90 && v[i] < 97 || v[i] > 122 {
errs.Add(key, &Error{Error: ErrNotAlphanumeric})
return
}
}
}
}
// Email rule checks that value represents an email.
func Email(errs Errors, form *multipart.Form, key string) {
if form == nil && form.Value == nil {
return
}
for _, v := range form.Value[key] {
if !reEmail.MatchString(v) {
errs.Add(key, &Error{Error: ErrNotEmail})
return
}
}
}
// FileType rule checks that file is one of given MIME types.
func FileType(types ...string) Rule {
return func(errs Errors, form *multipart.Form, key string) {
if form == nil && form.File == nil {
return
}
for _, file := range form.File[key] {
ct, err := fileType(file)
if err != nil {
continue
}
if !sliceContainsString(types, ct) {
errs.Add(key, &Error{Error: ErrBadFileType, Args: stringsToInterfaces(types)})
return
}
}
}
}
// Image rule checks that file is GIF, JPEG or PNG.
func Image(errs Errors, form *multipart.Form, key string) {
if form == nil && form.File == nil {
return
}
for _, file := range form.File[key] {
ct, err := fileType(file)
if err != nil {
continue
}
if !sliceContainsString([]string{"image/gif", "image/jpeg", "image/png"}, ct) {
errs.Add(key, &Error{Error: ErrNotImage})
return
}
}
}
// Integer rule checks that value represents an integer.
func Integer(errs Errors, form *multipart.Form, key string) {
if form == nil && form.Value == nil {
return
}
for _, v := range form.Value[key] {
if v == "." {
errs.Add(key, &Error{Error: ErrNotInteger})
return
}
if _, err := strconv.Atoi(v); err != nil {
errs.Add(key, &Error{Error: ErrNotInteger})
return
}
}
}
// Latitude rule checks that value represents a latitude.
func Latitude(errs Errors, form *multipart.Form, key string) {
if form == nil && form.Value == nil {
return
}
for _, v := range form.Value[key] {
f, err := strconv.ParseFloat(v, 64)
if err != nil {
errs.Add(key, &Error{Error: ErrNotNumber})
return
}
if f < -90 || f > 90 {
errs.Add(key, &Error{Error: ErrNotLatitude})
return
}
}
}
// Longitude rule checks that value represents a longitude.
func Longitude(errs Errors, form *multipart.Form, key string) {
if form == nil && form.Value == nil {
return
}
for _, v := range form.Value[key] {
f, err := strconv.ParseFloat(v, 64)
if err != nil {
errs.Add(key, &Error{Error: ErrNotNumber})
return
}
if f < -180 || f > 180 {
errs.Add(key, &Error{Error: ErrNotLongitude})
return
}
}
}
// Max rule checks that value is below or equals max.
func Max(max float64) Rule {
return func(errs Errors, form *multipart.Form, key string) {
if form == nil && form.Value == nil {
return
}
for _, v := range form.Value[key] {
f, err := strconv.ParseFloat(v, 64)
if err != nil {
errs.Add(key, &Error{Error: ErrNotNumber})
return
}
if f > max {
errs.Add(key, &Error{Error: ErrMax, Args: []interface{}{i18n.TransInt(max)}})
return
}
}
}
}
// MaxFileSize rule checks if file has max or less bytes.
func MaxFileSize(max int64) Rule {
return func(errs Errors, form *multipart.Form, key string) {
if form == nil && form.File == nil {
return
}
for _, file := range form.File[key] {
if file != nil && file.Size > max {
errs.Add(key, &Error{Error: ErrMaxFileSize, Args: []interface{}{i18n.TransFileSize(max)}})
return
}
}
}
}
// MaxLen rule checks that value length is below or equals max.
func MaxLen(max int) Rule {
return func(errs Errors, form *multipart.Form, key string) {
if form == nil && form.Value == nil {
return
}
for _, v := range form.Value[key] {
if len(v) > max {
errs.Add(key, &Error{Error: ErrMaxLen, Args: []interface{}{i18n.TransInt(max)}})
return
}
}
}
}
// Min rule checks that value is over or equals min.
func Min(min float64) Rule {
return func(errs Errors, form *multipart.Form, key string) {
if form == nil && form.Value == nil {
return
}
for _, v := range form.Value[key] {
f, err := strconv.ParseFloat(v, 64)
if err != nil {
errs.Add(key, &Error{Error: ErrNotNumber})
return
}
if f < min {
errs.Add(key, &Error{Error: ErrMin, Args: []interface{}{i18n.TransInt(min)}})
return
}
}
}
}
// MinFileSize rule checks if file has min or more bytes.
func MinFileSize(min int64) Rule {
return func(errs Errors, form *multipart.Form, key string) {
if form == nil && form.File == nil {
return
}
for _, file := range form.File[key] {
if file != nil && file.Size < min {
errs.Add(key, &Error{Error: ErrMinFileSize, Args: []interface{}{i18n.TransFileSize(min)}})
return
}
}
}
}
// MinLen rule checks that value length is over or equals min.
func MinLen(min int) Rule {
return func(errs Errors, form *multipart.Form, key string) {
if form == nil && form.Value == nil {
return
}
for _, v := range form.Value[key] {
if len(v) < min {
errs.Add(key, &Error{Error: ErrMinLen, Args: []interface{}{i18n.TransInt(min)}})
return
}
}
}
}
// Number rule checks that value represents a number.
func Number(errs Errors, form *multipart.Form, key string) {
if form == nil && form.Value == nil {
return
}
for _, v := range form.Value[key] {
_, err := strconv.ParseFloat(v, 64)
if err != nil {
errs.Add(key, &Error{Error: ErrNotNumber})
return
}
}
}
// Phone rule checks that value represents a phone number.
func Phone(errs Errors, form *multipart.Form, key string) {
if form == nil && form.Value == nil {
return
}
for _, v := range form.Value[key] {
if !rePhone.MatchString(v) {
errs.Add(key, &Error{Error: ErrNotPhone})
return
}
}
}
// Range rule checks that value represents a number inside a range.
func Range(min, max float64) Rule {
return func(errs Errors, form *multipart.Form, key string) {
if form == nil && form.Value == nil {
return
}
for _, v := range form.Value[key] {
f, err := strconv.ParseFloat(v, 64)
if err != nil {
errs.Add(key, &Error{Error: ErrNotNumber})
return
}
if f > max {
errs.Add(key, &Error{Error: ErrMax, Args: []interface{}{i18n.TransInt(max)}})
return
}
if f < min {
errs.Add(key, &Error{Error: ErrMin, Args: []interface{}{i18n.TransInt(min)}})
return
}
}
}
}
// RangeFileSize rule checks if file length is inside a range.
func RangeFileSize(min, max int64) Rule {
return func(errs Errors, form *multipart.Form, key string) {
if form == nil && form.File == nil {
return
}
for _, file := range form.File[key] {
if file == nil {
continue
}
if file.Size > max {
errs.Add(key, &Error{Error: ErrMaxFileSize, Args: []interface{}{i18n.TransFileSize(max)}})
return
}
if file.Size < min {
errs.Add(key, &Error{Error: ErrMinFileSize, Args: []interface{}{i18n.TransFileSize(min)}})
return
}
}
}
}
// RangeLen rule checks that value length is inside a range.
func RangeLen(min, max int) Rule {
return func(errs Errors, form *multipart.Form, key string) {
if form == nil && form.Value == nil {
return
}
for _, v := range form.Value[key] {
if len(v) > max {
errs.Add(key, &Error{Error: ErrMaxLen, Args: []interface{}{i18n.TransInt(max)}})
return
}
if len(v) < min {
errs.Add(key, &Error{Error: ErrMinLen, Args: []interface{}{i18n.TransInt(min)}})
return
}
}
}
}
// Required rule checks that value or file exists and is not empty.
// A value is not trimmed so a single space can pass the check.
func Required(errs Errors, form *multipart.Form, key string) {
if form == nil {
errs.Add(key, &Error{Error: ErrRequired})
return
}
if form.Value != nil {
for _, v := range form.Value[key] {
if v != "" {
return
}
}
}
if form.File != nil {
for _, v := range form.File[key] {
if v == nil {
return
}
}
}
errs.Add(key, &Error{Error: ErrRequired})
return
}
// Same rule checks that value deeply equals another key value.
func Same(keys ...string) Rule {
return func(errs Errors, form *multipart.Form, key string) {
if form == nil && form.Value == nil {
return
}
for _, k := range keys {
if !reflect.DeepEqual(form.Value[key], form.Value[k]) {
errs.Add(key, &Error{Error: ErrNotSame, Args: stringsToInterfaces(keys)})
return
}
}
}
}
// Unique rule checks that value is unique in database.
// The placeholder ("?", "$1" or other) must be provided as it depends on the SQL driver.
func Unique(db *sql.DB, table, column, placeholder string) Rule {
if db == nil {
panic(`check: no database provided for "unique" rule`)
}
return func(errs Errors, form *multipart.Form, key string) {
if _, ok := errs[key]; ok { // Avoid a database call if the format is already bad.
return
}
for _, v := range form.Value[key] {
var n int
if err := db.QueryRow("SELECT COUNT() FROM "+table+" WHERE "+column+" = "+placeholder, v).Scan(&n); err != nil {
panic(err)
}
if n > 0 {
errs.Add(key, &Error{Error: ErrNotUnique})
return
}
}
}
}
// URL rule checks that value represents an URL.
func URL(errs Errors, form *multipart.Form, key string) {
if form == nil && form.Value == nil {
return
}
for _, v := range form.Value[key] {
if len(v) < 4 {
errs.Add(key, &Error{Error: ErrNotURL})
return
}
v = strings.Replace(v, "127.0.0.1", "localhost", 1)
if i := strings.IndexByte(v, '#'); i != -1 {
v = v[:i]
}
if !strings.Contains(v, "://") {
v = "http://" + v
}
u, err := url.ParseRequestURI(v)
if err != nil || u.Host == "" || u.Host[0] == '-' || strings.Contains(u.Host, ".-") || strings.Contains(u.Host, "-.") {
errs.Add(key, &Error{Error: ErrNotURL})
return
}
parts := strings.Split(u.Host, ".")
if parts[0] == "" {
errs.Add(key, &Error{Error: ErrNotURL})
return
}
var domain string
if len(parts) > 2 {
domain = strings.Join(parts[len(parts)-2:], ".")
} else {
domain = strings.Join(parts, ".")
}
if strings.ContainsAny(domain, "_,&") {
errs.Add(key, &Error{Error: ErrNotURL})
return
}
if strings.Count(domain, "::") > 1 { // Only 1 substitution ("::") allowed in IPv6 address.
errs.Add(key, &Error{Error: ErrNotURL})
return
}
parts = strings.Split(domain, ":")
port, err := strconv.Atoi(parts[len(parts)-1])
if err == nil && (port < 1 || port > 65535) {
errs.Add(key, &Error{Error: ErrNotURL})
return
}
}
}