-
Notifications
You must be signed in to change notification settings - Fork 0
/
time.go
109 lines (91 loc) · 2.22 KB
/
time.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
package buzz
import (
"fmt"
"reflect"
"time"
)
var (
timeReflectType = reflect.TypeOf(time.Time{})
)
type BuzzTimeValidateFunc func(t time.Time) error
type BuzzTime struct {
name string
validateFuncs []BuzzTimeValidateFunc
}
func Time() *BuzzTime {
return &BuzzTime{}
}
func (t *BuzzTime) Name() string {
return t.name
}
func (t *BuzzTime) Type() reflect.Type {
return timeReflectType
}
func (t *BuzzTime) WithName(name string) BuzzField {
t.name = name
return t
}
func (t *BuzzTime) Validate(v any) error {
vtime, ok := v.(time.Time)
if !ok {
return fmt.Errorf(invalidTypeMsg, timeReflectType, v)
}
errAggr := NewFieldErrorAggregator()
for _, valFn := range t.validateFuncs {
if err := valFn(vtime); err != nil {
if errAggr.Handle(err) != nil {
return err
}
}
}
return errAggr.OrNil()
}
func (t *BuzzTime) Clone() BuzzField {
return &BuzzTime{
name: t.name,
validateFuncs: t.validateFuncs,
}
}
func (t *BuzzTime) After(timestamp time.Time) *BuzzTime {
t.registerValidateFunc(func(v time.Time) error {
if v.After(timestamp) {
return nil
}
return MakeFieldError(t.name, "After", fmt.Sprintf("%s must be after %s", t.name, timestamp))
})
return t
}
func (t *BuzzTime) Before(timestamp time.Time) *BuzzTime {
t.registerValidateFunc(func(v time.Time) error {
if v.Before(timestamp) {
return nil
}
return MakeFieldError(t.name, "Before", fmt.Sprintf("%s must be before %s", t.name, timestamp))
})
return t
}
func (t *BuzzTime) NotAfter(timestamp time.Time) *BuzzTime {
t.registerValidateFunc(func(v time.Time) error {
if v.After(timestamp) {
return MakeFieldError(t.name, "NotAfter", fmt.Sprintf("%s must not be after %s", t.name, timestamp))
}
return nil
})
return t
}
func (t *BuzzTime) NotBefore(timestamp time.Time) *BuzzTime {
t.registerValidateFunc(func(v time.Time) error {
if v.Before(timestamp) {
return MakeFieldError(t.name, "NotBefore", fmt.Sprintf("%s must not be before %s", t.name, timestamp))
}
return nil
})
return t
}
func (t *BuzzTime) Custom(fn BuzzTimeValidateFunc) *BuzzTime {
t.registerValidateFunc(fn)
return t
}
func (t *BuzzTime) registerValidateFunc(fn BuzzTimeValidateFunc) {
t.validateFuncs = append(t.validateFuncs, fn)
}