-
Notifications
You must be signed in to change notification settings - Fork 0
/
for_slice.go
49 lines (36 loc) · 1.2 KB
/
for_slice.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
package validator
import (
"context"
"reflect"
ve "github.com/donatorsky/go-validator/error"
vr "github.com/donatorsky/go-validator/rule"
)
type forSliceValidatorOption func(options *validatorOptions) error
func ForSlice(data any, rules []vr.Rule, options ...forSliceValidatorOption) (ve.ErrorsBag, error) {
return ForSliceWithContext(context.Background(), data, rules, options...)
}
func ForSliceWithContext(ctx context.Context, data any, rules []vr.Rule, options ...forSliceValidatorOption) (ve.ErrorsBag, error) {
data, _ = vr.Dereference(data)
if kind := reflect.TypeOf(data).Kind(); kind != reflect.Slice && kind != reflect.Array {
return nil, ve.NotListTypeError{}
}
opts := &validatorOptions{}
for _, option := range options {
if err := option(opts); err != nil {
return nil, err
}
}
errorsBag := ve.NewErrorsBag()
for fieldValue := range newFieldsIterator("*", data) {
if err := applyRules(ctx, data, rules, fieldValue, errorsBag, opts); err != nil {
return nil, err
}
}
return errorsBag, nil
}
func ForSliceWithDataCollector(collector DataCollector) forSliceValidatorOption {
return func(options *validatorOptions) error {
options.dataCollector = collector
return nil
}
}