-
Notifications
You must be signed in to change notification settings - Fork 19
/
validator_example_test.go
207 lines (177 loc) · 5.06 KB
/
validator_example_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
// Copyright 2023-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package protovalidate
import (
"errors"
"fmt"
"log"
"os"
"text/template"
pb "github.com/bufbuild/protovalidate-go/internal/gen/tests/example/v1"
"google.golang.org/protobuf/reflect/protoregistry"
)
func Example() {
person := &pb.Person{
Id: 1234,
Email: "[email protected]",
Name: "Buf Build",
Home: &pb.Coordinates{
Lat: 27.380583333333334,
Lng: 33.631838888888886,
},
}
err := Validate(person)
fmt.Println("valid:", err)
person.Email = "not an email"
err = Validate(person)
fmt.Println("invalid:", err)
// output:
// valid: <nil>
// invalid: validation error:
// - email: value must be a valid email address [string.email]
}
func ExampleWithFailFast() {
loc := &pb.Coordinates{Lat: 999.999, Lng: -999.999}
validator, err := New()
if err != nil {
log.Fatal(err)
}
err = validator.Validate(loc)
fmt.Println("default:", err)
validator, err = New(WithFailFast(true))
if err != nil {
log.Fatal(err)
}
err = validator.Validate(loc)
fmt.Println("fail fast:", err)
// output:
// default: validation error:
// - lat: value must be greater than or equal to -90 and less than or equal to 90 [double.gte_lte]
// - lng: value must be greater than or equal to -180 and less than or equal to 180 [double.gte_lte]
// fail fast: validation error:
// - lat: value must be greater than or equal to -90 and less than or equal to 90 [double.gte_lte]
}
func ExampleWithMessages() {
validator, err := New(
WithMessages(&pb.Person{}),
)
if err != nil {
log.Fatal(err)
}
person := &pb.Person{
Id: 1234,
Email: "[email protected]",
Name: "Protocol Buffer",
}
err = validator.Validate(person)
fmt.Println(err)
// output: <nil>
}
func ExampleWithDescriptors() {
pbType, err := protoregistry.GlobalTypes.FindMessageByName("tests.example.v1.Person")
if err != nil {
log.Fatal(err)
}
validator, err := New(
WithDescriptors(
pbType.Descriptor(),
),
)
if err != nil {
log.Fatal(err)
}
person := &pb.Person{
Id: 1234,
Email: "[email protected]",
Name: "Protocol Buffer",
}
err = validator.Validate(person)
fmt.Println(err)
// output: <nil>
}
func ExampleWithDisableLazy() {
person := &pb.Person{
Id: 1234,
Email: "[email protected]",
Name: "Buf Build",
Home: &pb.Coordinates{
Lat: 27.380583333333334,
Lng: 33.631838888888886,
},
}
validator, err := New(
WithMessages(&pb.Coordinates{}),
WithDisableLazy(true),
)
if err != nil {
log.Fatal(err)
}
err = validator.Validate(person.GetHome())
fmt.Println("person.Home:", err)
err = validator.Validate(person)
fmt.Println("person:", err)
// output:
// person.Home: <nil>
// person: compilation error: no evaluator available for tests.example.v1.Person
}
func ExampleValidationError() {
validator, err := New()
if err != nil {
log.Fatal(err)
}
loc := &pb.Coordinates{Lat: 999.999}
err = validator.Validate(loc)
var valErr *ValidationError
if ok := errors.As(err, &valErr); ok {
violation := valErr.Violations[0]
fmt.Println(FieldPathString(violation.Proto.GetField()), violation.Proto.GetConstraintId())
fmt.Println(violation.RuleValue, violation.FieldValue)
}
// output: lat double.gte_lte
// -90 999.999
}
func ExampleValidationError_localized() {
validator, err := New()
if err != nil {
log.Fatal(err)
}
type ErrorInfo struct {
FieldName string
RuleValue any
FieldValue any
}
var ruleMessages = map[string]string{
"string.email_empty": "{{.FieldName}}: メールアドレスは空であってはなりません。\n",
"string.pattern": "{{.FieldName}}: 値はパターン「{{.RuleValue}}」一致する必要があります。\n",
"uint64.gt": "{{.FieldName}}: 値は{{.RuleValue}}を超える必要があります。(価値:{{.FieldValue}})\n",
}
loc := &pb.Person{Id: 900}
err = validator.Validate(loc)
var valErr *ValidationError
if ok := errors.As(err, &valErr); ok {
for _, violation := range valErr.Violations {
_ = template.
Must(template.New("").Parse(ruleMessages[violation.Proto.GetConstraintId()])).
Execute(os.Stdout, ErrorInfo{
FieldName: FieldPathString(violation.Proto.GetField()),
RuleValue: violation.RuleValue.Interface(),
FieldValue: violation.FieldValue.Interface(),
})
}
}
// output:
// id: 値は999を超える必要があります。(価値:900)
// email: メールアドレスは空であってはなりません。
// name: 値はパターン「^[[:alpha:]]+( [[:alpha:]]+)*$」一致する必要があります。
}