-
Notifications
You must be signed in to change notification settings - Fork 3
/
in_range.go
99 lines (77 loc) · 1.5 KB
/
in_range.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
package validator
import "context"
type InRange struct {
message string
rangeValues []any
not bool
whenFunc WhenFunc
skipEmpty bool
skipError bool
}
func NewInRange(rangeValues []any) *InRange {
return &InRange{
message: "This value is invalid",
rangeValues: rangeValues,
not: false,
}
}
func (r *InRange) WithMessage(message string) *InRange {
rc := *r
rc.message = message
return &rc
}
func (r *InRange) Not() *InRange {
rc := *r
rc.not = true
return &rc
}
func (r *InRange) When(v WhenFunc) *InRange {
rc := *r
rc.whenFunc = v
return &rc
}
func (r *InRange) when() WhenFunc {
return r.whenFunc
}
func (r *InRange) setWhen(v WhenFunc) {
r.whenFunc = v
}
func (r *InRange) SkipOnEmpty() *InRange {
rc := *r
rc.skipEmpty = true
return &rc
}
func (r *InRange) skipOnEmpty() bool {
return r.skipEmpty
}
func (r *InRange) setSkipOnEmpty(v bool) {
r.skipEmpty = v
}
func (r *InRange) SkipOnError() *InRange {
rs := *r
rs.skipError = true
return &rs
}
func (r *InRange) shouldSkipOnError() bool {
return r.skipError
}
func (r *InRange) setSkipOnError(v bool) {
r.skipError = v
}
func (r *InRange) ValidateValue(_ context.Context, value any) error {
v, valid := indirectValue(value)
if !valid {
return NewResult().WithError(NewValidationError(r.message))
}
var in bool
for _, rv := range r.rangeValues {
if rv == v {
in = true
break
}
}
if r.not == in {
return NewResult().WithError(NewValidationError(r.message))
}
return nil
}