-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathslice.go
More file actions
62 lines (53 loc) · 1.52 KB
/
slice.go
File metadata and controls
62 lines (53 loc) · 1.52 KB
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
package validate
import "fmt"
// Slice will run the validators on each element in the slice.
func Slice[F ~string, T any](name F, value []T) SliceValidator[T] {
return SliceValidator[T]{
name: string(name),
value: value,
}
}
type SliceValidator[T any] struct {
name string
value []T
}
func (v SliceValidator[T]) Items(field string, validators ...Validator[T]) error {
var verrs Errors
path := fmt.Sprintf("%s.*", v.name)
for i, value := range v.value {
violations, err := validate(value, validators...)
if err != nil {
// It could be that the validators returned an Error or Errors. If so we map it with the correct paths.
if isValidationError(err) {
switch err := err.(type) {
case Error:
verrs = verrs.merge(prefixSliceError(err, v.name, field, i))
case Errors:
verrs = verrs.mergeAll(err.mapErrors(func(err Error) Error {
return prefixSliceError(err, v.name, field, i)
}))
}
} else {
return err
}
}
if len(violations) > 0 {
verrs = append(verrs, Error{
Path: path + "." + field,
ExactPath: fmt.Sprintf("%s.%d.%s", v.name, i, field),
Violations: violations,
Args: Args{"index": i},
})
}
}
if len(verrs) == 0 {
return nil
}
return verrs
}
func prefixSliceError(err Error, name string, field string, index int) Error {
err.Path = prefixPath(err.Path, fmt.Sprintf("%s.*.%s", name, field))
err.ExactPath = prefixPath(err.ExactPath, fmt.Sprintf("%s.%d.%s", name, index, field))
err.Args = err.Args.Add("index", index)
return err
}