-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexample_validatable_slice_test.go
57 lines (47 loc) · 1.55 KB
/
example_validatable_slice_test.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
package validation_test
import (
"context"
"fmt"
"github.com/muonsoft/validation"
"github.com/muonsoft/validation/it"
"github.com/muonsoft/validation/validator"
)
type Company struct {
Name string
Address string
}
type Companies []Company
func (companies Companies) Validate(ctx context.Context, validator *validation.Validator) error {
violations := validation.ViolationList{}
for i, company := range companies {
err := validator.AtIndex(i).Validate(
ctx,
validation.StringProperty("name", company.Name, it.IsNotBlank()),
validation.StringProperty("address", company.Address, it.IsNotBlank(), it.HasMinLength(3)),
)
// appending violations from err
err = violations.AppendFromError(err)
// if append returns a non-nil error we should stop validation because an internal error occurred
if err != nil {
return err
}
}
// we should always convert ViolationList into error by calling the AsError method
// otherwise empty violations list will be interpreted as an error
return violations.AsError()
}
func ExampleValid_validatableSlice() {
companies := Companies{
{"MuonSoft", "London"},
{"", "x"},
}
err := validator.Validate(context.Background(), validation.Valid(companies))
if violations, ok := validation.UnwrapViolationList(err); ok {
for violation := violations.First(); violation != nil; violation = violation.Next() {
fmt.Println(violation)
}
}
// Output:
// violation at "[1].name": "This value should not be blank."
// violation at "[1].address": "This value is too short. It should have 3 characters or more."
}