-
Notifications
You must be signed in to change notification settings - Fork 0
/
validate.go
109 lines (94 loc) · 1.99 KB
/
validate.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 fork
import "reflect"
type Validater interface {
Validateable() bool
SetValidateable(bool) bool
Validate(Field) error
Valid(Field) bool
Error(Field) bool
Errors(Field) []string
Validaters(...interface{}) []reflect.Value
}
var nilValidater = &validater{}
type validater struct {
validateable bool
validaters []reflect.Value
}
func NewValidater(v ...interface{}) Validater {
return &validater{validaters: reflectValidaters(v...)}
}
func (v *validater) Validateable() bool {
return v.validateable
}
func (v *validater) SetValidateable(b bool) bool {
v.validateable = b
return v.Validateable()
}
func (v *validater) Validate(f Field) error {
var err error
if v.validateable {
for _, vdr := range v.validaters {
err = Validate(vdr, f)
if err != nil {
return err
}
}
}
return err
}
func (v *validater) Valid(f Field) bool {
var valid = true
if v.validateable {
err := v.Validate(f)
if err != nil {
valid = false
}
}
return valid
}
func (v *validater) Error(f Field) bool {
if v.validateable {
return !v.Valid(f)
}
return false
}
func (v *validater) Errors(f Field) []string {
var ret []string
if v.validateable {
for _, vdr := range v.validaters {
err := Validate(vdr, f)
if err != nil {
ret = append(ret, err.Error())
}
}
}
return ret
}
func (v *validater) Validaters(fns ...interface{}) []reflect.Value {
v.validaters = append(v.validaters, reflectValidaters(fns...)...)
return v.validaters
}
func reflectValidaters(fns ...interface{}) []reflect.Value {
var ret []reflect.Value
for _, fn := range fns {
ret = append(ret, valueFn(fn, isValidater, `1 value and the value must be an error`))
}
return ret
}
func isValidater(typ reflect.Type) bool {
switch {
case typ.NumOut() == 1 && typ.Out(0) == errorType:
return true
}
return false
}
func Validate(fn reflect.Value, args ...interface{}) error {
validated, err := call(fn, args...)
if err != nil {
return err
}
if validated != nil {
return validated.(error)
}
return nil
}