-
Notifications
You must be signed in to change notification settings - Fork 3
/
slice.go
68 lines (58 loc) · 2.05 KB
/
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package goval
import (
"context"
"github.com/pkg-id/goval/funcs"
)
// SliceValidator is a FunctionValidator that validates slices.
type SliceValidator[T any, V []T] FunctionValidator[V]
// Slice returns a SliceValidator with no rules.
// T is the type of the slice elements, V is the type of the slice.
func Slice[T any, V []T]() SliceValidator[T, V] {
return NopFunctionValidator[V]
}
// Validate executes the validation rules immediately.
func (f SliceValidator[T, V]) Validate(ctx context.Context, values V) error {
return validatorOf(f, values).Validate(ctx)
}
// With attaches the next rule to the chain.
func (f SliceValidator[T, V]) With(next SliceValidator[T, V]) SliceValidator[T, V] {
return Chain(f, next)
}
// Required ensures the slice is not empty.
func (f SliceValidator[T, V]) Required() SliceValidator[T, V] {
return f.With(func(ctx context.Context, values V) error {
if len(values) == 0 {
return NewRuleError(SliceRequired)
}
return nil
})
}
// Min ensures the length of the slice is not less than the given min.
func (f SliceValidator[T, V]) Min(min int) SliceValidator[T, V] {
return f.With(func(ctx context.Context, values V) error {
if len(values) < min {
return NewRuleError(SliceMin, min)
}
return nil
})
}
// Max ensures the length of the slice is not greater than the given max.
func (f SliceValidator[T, V]) Max(max int) SliceValidator[T, V] {
return f.With(func(ctx context.Context, values V) error {
if len(values) > max {
return NewRuleError(SliceMax, max)
}
return nil
})
}
// Each ensures each element of the slice is satisfied by the given validator.
func (f SliceValidator[T, V]) Each(validator RuleValidator[T]) SliceValidator[T, V] {
return f.With(func(ctx context.Context, values V) error {
validators := funcs.Map(values, RuleValidatorToValidatorFactory(validator))
return execute(ctx, validators)
})
}
// EachFunc ensures each element of the slice is satisfied by the given validator.
func (f SliceValidator[T, V]) EachFunc(validator RuleValidatorFunc[T]) SliceValidator[T, V] {
return f.Each(validator)
}