Passed
Pull Request — main (#52)
by Igor
02:16
created

example_validatable_struct_test.go   A

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 34
dl 0
loc 54
rs 10
c 0
b 0
f 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 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
	if violations, ok := validation.UnwrapViolationList(err); ok {
53
		for violation := violations.First(); violation != nil; violation = violation.Next() {
54
			fmt.Println(violation)
55
		}
56
	}
57
	// Output:
58
	// violation at 'name': This value should not be blank.
59
	// violation at 'tags': This collection should contain 1 element or more.
60
	// violation at 'components[0].name': This value should not be blank.
61
	// violation at 'components[0].tags': This collection should contain 1 element or more.
62
}
63