Passed
Push — main ( 66a50b...113ff1 )
by Rushan
59s queued 11s
created

alidateValidatable_validatableSlice   A

Complexity

Conditions 2

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 8
dl 0
loc 11
rs 10
c 0
b 0
f 0
nop 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
	}
51
	// Output:
52
	// violation at '[1].name': This value should not be blank.
53
	// violation at '[1].address': This value is too short. It should have 3 characters or more.
54
}
55