Test Failed
Pull Request — main (#36)
by Rushan
02:31
created

alidate_structValidationWithConditionalConstraint   A

Complexity

Conditions 2

Size

Total Lines 22
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 17
dl 0
loc 22
rs 9.55
c 0
b 0
f 0
nop 0
1
package validation_test
2
3
import (
4
	"fmt"
5
	"regexp"
6
7
	"github.com/muonsoft/validation"
8
	"github.com/muonsoft/validation/it"
9
	"github.com/muonsoft/validation/validator"
10
)
11
12
type Document struct {
13
	Title    string
14
	Keywords []string
15
}
16
17
func ExampleValidator_Validate_basicStructValidation() {
18
	document := Document{
19
		Title:    "",
20
		Keywords: []string{""},
21
	}
22
23
	err := validator.Validate(
24
		validation.StringProperty("title", &document.Title, it.IsNotBlank()),
25
		validation.CountableProperty("keywords", len(document.Keywords), it.HasCountBetween(2, 10)),
26
		validation.EachStringProperty("keywords", document.Keywords, it.IsNotBlank()),
27
	)
28
29
	violations := err.(validation.ViolationList)
30
	for _, violation := range violations {
31
		fmt.Println(violation.Error())
32
	}
33
	// Output:
34
	// violation at 'title': This value should not be blank.
35
	// violation at 'keywords': This collection should contain 2 elements or more.
36
	// violation at 'keywords[0]': This value should not be blank.
37
}
38
39
func ExampleValidator_Validate_structValidationWithConditionalConstraint() {
40
	document := Document{
41
		Title:    "",
42
		Keywords: []string{"123", "test"},
43
	}
44
45
	err := validator.Validate(
46
		validation.StringProperty("title", &document.Title, it.IsNotBlank()),
47
		validation.CountableProperty("keywords", len(document.Keywords), it.HasCountBetween(2, 10)),
48
		validation.EachStringProperty(
49
			"keywords",
50
			document.Keywords,
51
			it.IsNotBlank(),
52
			validation.When(len(document.Title) <= 5).
53
				Then(it.Matches(regexp.MustCompile(`^\\d$`))).
54
				Else(it.Matches(regexp.MustCompile(`^\\w$`))),
55
		),
56
	)
57
58
	violations := err.(validation.ViolationList)
59
	for _, violation := range violations {
60
		fmt.Println(violation.Error())
61
	}
62
	// Output:
63
	// violation at 'title': This value should not be blank.
64
	// violation at 'keywords': This collection should contain 2 elements or more.
65
	// violation at 'keywords[1]': This value is not valid.
66
}
67