-
Notifications
You must be signed in to change notification settings - Fork 0
/
struct.go
64 lines (58 loc) · 1.3 KB
/
struct.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 validator
import (
"fmt"
"reflect"
)
func Struct(data any, fields Fields) RuleFunc {
return func() Rule {
return Rule{
Name: "struct",
ErrorMessage: func(r Rule) string {
return fmt.Sprintf("%s is not a struct", r.Target)
},
Validator: func(r Rule) (bool, ErrorList) {
val := reflect.ValueOf(r.GivenValue)
if val.Kind() != reflect.Struct {
return false, nil
}
sv := New(data, fields)
ok := sv.Validate()
return ok, sv.Errors()
},
}
}
}
func ArrayOfStructs(data any, fields Fields) RuleFunc {
return func() Rule {
return Rule{
Name: "arrayOfStructs",
ErrorMessage: func(r Rule) string {
return fmt.Sprintf("%s is not an array of structs", r.Target)
},
Validator: func(r Rule) (bool, ErrorList) {
val := reflect.ValueOf(r.GivenValue)
switch val.Kind() {
case reflect.Slice, reflect.Array:
if val.Index(0).Kind() != reflect.Struct {
return false, nil
}
errs := make(ErrorList)
var res bool
for i, s := range r.GivenValue.([]any) {
sv := New(s, fields)
ok := sv.Validate()
if !ok {
res = false
for k, e := range sv.Errors() {
errs[fmt.Sprintf("%d.%s", i, k)] = e
}
}
}
return res, errs
default:
return false, nil
}
},
}
}
}