|
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 Product struct { |
|
12
|
|
|
Name string |
|
13
|
|
|
Tags []string |
|
14
|
|
|
Components []Component |
|
15
|
|
|
} |
|
16
|
|
|
|
|
17
|
|
|
func (p Product) Validate(validator *validation.Validator) error { |
|
18
|
|
|
return validator.Validate( |
|
19
|
|
|
validation.StringProperty("name", &p.Name, it.IsNotBlank()), |
|
20
|
|
|
validation.IterableProperty("tags", p.Tags, it.HasMinCount(1)), |
|
21
|
|
|
// this also runs validation on each of the components |
|
22
|
|
|
validation.IterableProperty("components", p.Components, it.HasMinCount(1)), |
|
23
|
|
|
) |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
type Component struct { |
|
27
|
|
|
ID int |
|
28
|
|
|
Name string |
|
29
|
|
|
Tags []string |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
func (c Component) Validate(validator *validation.Validator) error { |
|
33
|
|
|
return validator.Validate( |
|
34
|
|
|
validation.StringProperty("name", &c.Name, it.IsNotBlank()), |
|
35
|
|
|
validation.CountableProperty("tags", len(c.Tags), it.HasMinCount(1)), |
|
36
|
|
|
) |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
func ExampleValidator_ValidateValidatable_validatableStruct() { |
|
40
|
|
|
p := Product{ |
|
41
|
|
|
Name: "", |
|
42
|
|
|
Components: []Component{ |
|
43
|
|
|
{ |
|
44
|
|
|
ID: 1, |
|
45
|
|
|
Name: "", |
|
46
|
|
|
}, |
|
47
|
|
|
}, |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
err := validator.ValidateValidatable(p) |
|
51
|
|
|
|
|
52
|
|
|
violations := err.(validation.ViolationList) |
|
53
|
|
|
for _, violation := range violations { |
|
54
|
|
|
fmt.Println(violation.Error()) |
|
55
|
|
|
} |
|
56
|
|
|
// Output: |
|
57
|
|
|
// violation at 'name': This value should not be blank. |
|
58
|
|
|
// violation at 'tags': This collection should contain 1 element or more. |
|
59
|
|
|
// violation at 'components[0].name': This value should not be blank. |
|
60
|
|
|
// violation at 'components[0].tags': This collection should contain 1 element or more. |
|
61
|
|
|
} |
|
62
|
|
|
|