-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvalidation.go
85 lines (76 loc) · 2.01 KB
/
validation.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
package qp
import (
"github.com/pkg/errors"
)
// ValidationFunc represents a validator for Filters.
type ValidationFunc func(value interface{}) error
// Validations type replacement for map.
// Used in NewParse(), NewQV(), SetValidations().
type Validations map[string]ValidationFunc
// Multi combines multiple validation functions.
// Usage: Multi(Min(10), Max(100)).
func Multi(validators ...ValidationFunc) ValidationFunc {
return func(value interface{}) error {
for _, validator := range validators {
if err := validator(value); err != nil {
return err
}
}
return nil
}
}
// In checks if the value is within the provided values.
func In(validValues ...interface{}) ValidationFunc {
return func(value interface{}) error {
for _, validValue := range validValues {
if validValue == value {
return nil
}
}
return errors.Wrapf(ErrNotInScope, "%v", value)
}
}
// Min checks if the value is greater than or equal to the minimum.
func Min(min int) ValidationFunc {
return func(value interface{}) error {
if intValue, ok := value.(int); ok {
if intValue >= min {
return nil
}
}
return errors.Wrapf(ErrNotInScope, "%v", value)
}
}
// Max checks if the value is less than or equal to the maximum.
func Max(max int) ValidationFunc {
return func(value interface{}) error {
if intValue, ok := value.(int); ok {
if intValue <= max {
return nil
}
}
return errors.Wrapf(ErrNotInScope, "%v", value)
}
}
// MinMax checks if the value is between or equal to the minimum and maximum.
func MinMax(min, max int) ValidationFunc {
return func(value interface{}) error {
if intValue, ok := value.(int); ok {
if min <= intValue && intValue <= max {
return nil
}
}
return errors.Wrapf(ErrNotInScope, "%v", value)
}
}
// NotEmpty checks if the string value is not empty.
func NotEmpty() ValidationFunc {
return func(value interface{}) error {
if str, ok := value.(string); ok {
if len(str) > 0 {
return nil
}
}
return errors.Wrapf(ErrNotInScope, "%v", value)
}
}