-
Notifications
You must be signed in to change notification settings - Fork 0
/
in.go
64 lines (53 loc) · 1.03 KB
/
in.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
package validation
import "time"
var ErrInInvalid = NewRuleError("in_invalid", "must be a valid value")
type inRule[T comparable] struct {
elements []T
}
func In[T comparable](elements ...T) inRule[T] {
return inRule[T]{
elements: elements,
}
}
func (r inRule[T]) Validate(v T) error {
for i := range r.elements {
if r.elements[i] == v {
return nil
}
}
return ErrInInvalid
}
type inAnyRule[T any] struct {
elements []T
eq func(a, b T) bool
}
func InAny[T any](eq func(a, b T) bool, elements ...T) inAnyRule[T] {
return inAnyRule[T]{
elements: elements,
eq: eq,
}
}
func (r inAnyRule[T]) Validate(v T) error {
for i := range r.elements {
if r.eq(r.elements[i], v) {
return nil
}
}
return ErrInInvalid
}
type inTimeRule struct {
elements []time.Time
}
func InTime(elements ...time.Time) inTimeRule {
return inTimeRule{
elements: elements,
}
}
func (r inTimeRule) Validate(t time.Time) error {
for i := range r.elements {
if t.Equal(r.elements[i]) {
return nil
}
}
return ErrInInvalid
}