Total Lines | 49 |
Duplicated Lines | 0 % |
Changes | 0 |
1 | package validation_test |
||
2 | |||
3 | import ( |
||
4 | "fmt" |
||
5 | |||
6 | "github.com/muonsoft/validation" |
||
7 | "github.com/muonsoft/validation/it" |
||
8 | "github.com/muonsoft/validation/validator" |
||
9 | ) |
||
10 | |||
11 | type Company struct { |
||
12 | Name string |
||
13 | Address string |
||
14 | } |
||
15 | |||
16 | type Companies []Company |
||
17 | |||
18 | func (companies Companies) Validate(validator *validation.Validator) error { |
||
19 | violations := validation.ViolationList{} |
||
20 | |||
21 | for i, company := range companies { |
||
22 | err := validator.AtIndex(i).Validate( |
||
23 | validation.StringProperty("name", &company.Name, it.IsNotBlank()), |
||
24 | validation.StringProperty("address", &company.Address, it.IsNotBlank(), it.HasMinLength(3)), |
||
25 | ) |
||
26 | // appending violations from err |
||
27 | err = violations.AppendFromError(err) |
||
28 | // if append returns a non-nil error we should stop validation because an internal error occurred |
||
29 | if err != nil { |
||
30 | return err |
||
31 | } |
||
32 | } |
||
33 | |||
34 | // we should always convert ViolationList into error by calling the AsError method |
||
35 | // otherwise empty violations list will be interpreted as an error |
||
36 | return violations.AsError() |
||
37 | } |
||
38 | |||
39 | func ExampleValidator_ValidateValidatable_validatableSlice() { |
||
40 | companies := Companies{ |
||
41 | {"MuonSoft", "London"}, |
||
42 | {"", "x"}, |
||
43 | } |
||
44 | |||
45 | err := validator.ValidateValidatable(companies) |
||
46 | |||
47 | violations := err.(validation.ViolationList) |
||
48 | for _, violation := range violations { |
||
49 | fmt.Println(violation.Error()) |
||
50 | } |
||
55 |