Passed
Push — main ( 3f29c3...92079a )
by Rushan
58s queued 10s
created

validation_test.ExampleBoolProperty   A

Complexity

Conditions 1

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 7
nop 0
dl 0
loc 10
rs 10
c 0
b 0
f 0
1
package validation_test
2
3
import (
4
	"context"
5
	"fmt"
6
	"log"
7
	"regexp"
8
	"time"
9
10
	languagepkg "github.com/muonsoft/language"
11
	"github.com/muonsoft/validation"
12
	"github.com/muonsoft/validation/it"
13
	"github.com/muonsoft/validation/message/translations/russian"
14
	"github.com/muonsoft/validation/validator"
15
	"golang.org/x/text/feature/plural"
16
	"golang.org/x/text/language"
17
	"golang.org/x/text/message/catalog"
18
)
19
20
func ExampleValue() {
21
	v := ""
22
	err := validator.Validate(validation.Value(v, it.IsNotBlank()))
23
	fmt.Println(err)
24
	// Output:
25
	// violation: This value should not be blank.
26
}
27
28
func ExamplePropertyValue() {
29
	v := Book{Title: ""}
30
	err := validator.Validate(
31
		validation.PropertyValue("title", v.Title, it.IsNotBlank()),
32
	)
33
	fmt.Println(err)
34
	// Output:
35
	// violation at 'title': This value should not be blank.
36
}
37
38
func ExampleBool() {
39
	v := false
40
	err := validator.Validate(validation.Bool(&v, it.IsTrue()))
41
	fmt.Println(err)
42
	// Output:
43
	// violation: This value should be true.
44
}
45
46
func ExampleBoolProperty() {
47
	v := struct {
48
		IsPublished bool
49
	}{
50
		IsPublished: false,
51
	}
52
	err := validator.Validate(
53
		validation.BoolProperty("isPublished", &v.IsPublished, it.IsTrue()),
54
	)
55
	fmt.Println(err)
56
	// Output:
57
	// violation at 'isPublished': This value should be true.
58
}
59
60
func ExampleNumber() {
61
	v := 5
62
	err := validator.Validate(validation.Number(&v, it.IsGreaterThanInteger(5)))
63
	fmt.Println(err)
64
	// Output:
65
	// violation: This value should be greater than 5.
66
}
67
68
func ExampleNumberProperty() {
69
	v := struct {
70
		Count int
71
	}{
72
		Count: 5,
73
	}
74
	err := validator.Validate(
75
		validation.NumberProperty("count", &v.Count, it.IsGreaterThanInteger(5)),
76
	)
77
	fmt.Println(err)
78
	// Output:
79
	// violation at 'count': This value should be greater than 5.
80
}
81
82
func ExampleString() {
83
	v := ""
84
	err := validator.Validate(validation.String(&v, it.IsNotBlank()))
85
	fmt.Println(err)
86
	// Output:
87
	// violation: This value should not be blank.
88
}
89
90
func ExampleStringProperty() {
91
	v := Book{Title: ""}
92
	err := validator.Validate(
93
		validation.StringProperty("title", &v.Title, it.IsNotBlank()),
94
	)
95
	fmt.Println(err)
96
	// Output:
97
	// violation at 'title': This value should not be blank.
98
}
99
100
func ExampleIterable() {
101
	v := make([]string, 0)
102
	err := validator.Validate(validation.Iterable(v, it.IsNotBlank()))
103
	fmt.Println(err)
104
	// Output:
105
	// violation: This value should not be blank.
106
}
107
108
func ExampleIterableProperty() {
109
	v := Product{Tags: []string{}}
110
	err := validator.Validate(
111
		validation.IterableProperty("tags", v.Tags, it.IsNotBlank()),
112
	)
113
	fmt.Println(err)
114
	// Output:
115
	// violation at 'tags': This value should not be blank.
116
}
117
118
func ExampleCountable() {
119
	s := []string{"a", "b"}
120
	err := validator.Validate(validation.Countable(len(s), it.HasMinCount(3)))
121
	fmt.Println(err)
122
	// Output:
123
	// violation: This collection should contain 3 elements or more.
124
}
125
126
func ExampleCountableProperty() {
127
	v := Product{Tags: []string{"a", "b"}}
128
	err := validator.Validate(
129
		validation.CountableProperty("tags", len(v.Tags), it.HasMinCount(3)),
130
	)
131
	fmt.Println(err)
132
	// Output:
133
	// violation at 'tags': This collection should contain 3 elements or more.
134
}
135
136
func ExampleTime() {
137
	t := time.Now()
138
	compared, _ := time.Parse(time.RFC3339, "2006-01-02T15:00:00Z")
139
	err := validator.Validate(
140
		validation.Time(&t, it.IsEarlierThan(compared)),
141
	)
142
	fmt.Println(err)
143
	// Output:
144
	// violation: This value should be earlier than 2006-01-02T15:00:00Z.
145
}
146
147
func ExampleTimeProperty() {
148
	v := struct {
149
		CreatedAt time.Time
150
	}{
151
		CreatedAt: time.Now(),
152
	}
153
	compared, _ := time.Parse(time.RFC3339, "2006-01-02T15:00:00Z")
154
	err := validator.Validate(
155
		validation.TimeProperty("createdAt", &v.CreatedAt, it.IsEarlierThan(compared)),
156
	)
157
	fmt.Println(err)
158
	// Output:
159
	// violation at 'createdAt': This value should be earlier than 2006-01-02T15:00:00Z.
160
}
161
162
func ExampleEach() {
163
	v := []string{""}
164
	err := validator.Validate(validation.Each(v, it.IsNotBlank()))
165
	fmt.Println(err)
166
	// Output:
167
	// violation at '[0]': This value should not be blank.
168
}
169
170
func ExampleEachProperty() {
171
	v := Product{Tags: []string{""}}
172
	err := validator.Validate(
173
		validation.EachProperty("tags", v.Tags, it.IsNotBlank()),
174
	)
175
	fmt.Println(err)
176
	// Output:
177
	// violation at 'tags[0]': This value should not be blank.
178
}
179
180
func ExampleEachString() {
181
	v := []string{""}
182
	err := validator.Validate(validation.EachString(v, it.IsNotBlank()))
183
	fmt.Println(err)
184
	// Output:
185
	// violation at '[0]': This value should not be blank.
186
}
187
188
func ExampleEachStringProperty() {
189
	v := Product{Tags: []string{""}}
190
	err := validator.Validate(
191
		validation.EachStringProperty("tags", v.Tags, it.IsNotBlank()),
192
	)
193
	fmt.Println(err)
194
	// Output:
195
	// violation at 'tags[0]': This value should not be blank.
196
}
197
198
func ExampleNewCustomStringConstraint() {
199
	validate := func(s string) bool {
200
		return s == "valid"
201
	}
202
	constraint := validation.NewCustomStringConstraint(
203
		validate,
204
		"ExampleConstraint", // constraint name
205
		"exampleCode",       // violation code
206
		"Unexpected value.", // violation message template
207
	)
208
209
	s := "foo"
210
	err := validator.ValidateString(&s, constraint)
211
212
	fmt.Println(err)
213
	// Output:
214
	// violation: Unexpected value.
215
}
216
217
func ExampleConditionalConstraint_Then() {
218
	v := "foo"
219
	err := validator.ValidateString(
220
		&v,
221
		validation.When(true).
222
			Then(
223
				it.Matches(regexp.MustCompile(`^\w+$`)),
224
			),
225
	)
226
	fmt.Println(err)
227
	// Output:
228
	// <nil>
229
}
230
231
func ExampleConditionalConstraint_Else() {
232
	v := "123"
233
	err := validator.ValidateString(
234
		&v,
235
		validation.When(false).
236
			Then(
237
				it.Matches(regexp.MustCompile(`^\w+$`)),
238
			).
239
			Else(
240
				it.Matches(regexp.MustCompile(`^\d+$`)),
241
			),
242
	)
243
	fmt.Println(err)
244
	// Output:
245
	// <nil>
246
}
247
248
func ExampleSequentially() {
249
	title := "bar"
250
251
	err := validator.ValidateString(
252
		&title,
253
		validation.Sequentially(
254
			it.IsBlank(),
255
			it.HasMinLength(5),
256
		),
257
	)
258
259
	violations := err.(validation.ViolationList)
260
	for _, violation := range violations {
261
		fmt.Println(violation.Error())
262
	}
263
	// Output:
264
	// violation: This value should be blank.
265
}
266
267
func ExampleValidator_Validate_basicValidation() {
268
	s := ""
269
270
	validator, err := validation.NewValidator()
271
	if err != nil {
272
		log.Fatal(err)
273
	}
274
	err = validator.Validate(validation.String(&s, it.IsNotBlank()))
275
276
	violations := err.(validation.ViolationList)
277
	for _, violation := range violations {
278
		fmt.Println(violation.Error())
279
	}
280
	// Output:
281
	// violation: This value should not be blank.
282
}
283
284
func ExampleValidator_Validate_singletonValidator() {
285
	s := ""
286
287
	err := validator.Validate(validation.String(&s, it.IsNotBlank()))
288
289
	violations := err.(validation.ViolationList)
290
	for _, violation := range violations {
291
		fmt.Println(violation.Error())
292
	}
293
	// Output:
294
	// violation: This value should not be blank.
295
}
296
297
func ExampleValidator_ValidateString_shorthandAlias() {
298
	s := ""
299
300
	err := validator.ValidateString(&s, it.IsNotBlank())
301
302
	violations := err.(validation.ViolationList)
303
	for _, violation := range violations {
304
		fmt.Println(violation.Error())
305
	}
306
	// Output:
307
	// violation: This value should not be blank.
308
}
309
310
func ExampleValidator_Validate_conditionalValidationOnConstraint() {
311
	notes := []struct {
312
		Title    string
313
		IsPublic bool
314
		Text     string
315
	}{
316
		{Title: "published note", IsPublic: true, Text: "text of published note"},
317
		{Title: "draft note", IsPublic: true, Text: ""},
318
	}
319
320
	for i, note := range notes {
321
		err := validator.Validate(
322
			validation.StringProperty("name", &note.Title, it.IsNotBlank()),
323
			validation.StringProperty("text", &note.Text, it.IsNotBlank().When(note.IsPublic)),
324
		)
325
		if err != nil {
326
			violations := err.(validation.ViolationList)
327
			for _, violation := range violations {
328
				fmt.Printf("error on note %d: %s", i, violation.Error())
329
			}
330
		}
331
	}
332
333
	// Output:
334
	// error on note 1: violation at 'text': This value should not be blank.
335
}
336
337
func ExampleValidator_Validate_passingPropertyPathViaOptions() {
338
	s := ""
339
340
	err := validator.Validate(
341
		validation.String(
342
			&s,
343
			validation.PropertyName("properties"),
344
			validation.ArrayIndex(1),
345
			validation.PropertyName("tag"),
346
			it.IsNotBlank(),
347
		),
348
	)
349
350
	violation := err.(validation.ViolationList)[0]
351
	fmt.Println("property path:", violation.PropertyPath().String())
352
	// Output:
353
	// property path: properties[1].tag
354
}
355
356
func ExampleValidator_Validate_propertyPathWithScopedValidator() {
357
	s := ""
358
359
	err := validator.
360
		AtProperty("properties").
361
		AtIndex(1).
362
		AtProperty("tag").
363
		Validate(validation.String(&s, it.IsNotBlank()))
364
365
	violation := err.(validation.ViolationList)[0]
366
	fmt.Println("property path:", violation.PropertyPath().String())
367
	// Output:
368
	// property path: properties[1].tag
369
}
370
371
func ExampleValidator_Validate_propertyPathBySpecialArgument() {
372
	s := ""
373
374
	err := validator.Validate(
375
		// this is an alias for
376
		// validation.String(&s, validation.PropertyName("property"), it.IsNotBlank()),
377
		validation.StringProperty("property", &s, it.IsNotBlank()),
378
	)
379
380
	violation := err.(validation.ViolationList)[0]
381
	fmt.Println("property path:", violation.PropertyPath().String())
382
	// Output:
383
	// property path: property
384
}
385
386
func ExampleValidator_AtProperty() {
387
	book := &Book{Title: ""}
388
389
	err := validator.AtProperty("book").Validate(
390
		validation.StringProperty("title", &book.Title, it.IsNotBlank()),
391
	)
392
393
	violation := err.(validation.ViolationList)[0]
394
	fmt.Println("property path:", violation.PropertyPath().String())
395
	// Output:
396
	// property path: book.title
397
}
398
399
func ExampleValidator_AtIndex() {
400
	books := []Book{{Title: ""}}
401
402
	err := validator.AtIndex(0).Validate(
403
		validation.StringProperty("title", &books[0].Title, it.IsNotBlank()),
404
	)
405
406
	violation := err.(validation.ViolationList)[0]
407
	fmt.Println("property path:", violation.PropertyPath().String())
408
	// Output:
409
	// property path: [0].title
410
}
411
412
func ExampleValidator_Validate_translationsByDefaultLanguage() {
413
	validator, err := validation.NewValidator(
414
		validation.Translations(russian.Messages),
415
		validation.DefaultLanguage(language.Russian),
416
	)
417
	if err != nil {
418
		log.Fatal(err)
419
	}
420
421
	s := ""
422
	err = validator.ValidateString(&s, it.IsNotBlank())
423
424
	violations := err.(validation.ViolationList)
425
	for _, violation := range violations {
426
		fmt.Println(violation.Error())
427
	}
428
	// Output:
429
	// violation: Значение не должно быть пустым.
430
}
431
432
func ExampleValidator_Validate_translationsByArgument() {
433
	validator, err := validation.NewValidator(
434
		validation.Translations(russian.Messages),
435
	)
436
	if err != nil {
437
		log.Fatal(err)
438
	}
439
440
	s := ""
441
	err = validator.Validate(
442
		validation.Language(language.Russian),
443
		validation.String(&s, it.IsNotBlank()),
444
	)
445
446
	violations := err.(validation.ViolationList)
447
	for _, violation := range violations {
448
		fmt.Println(violation.Error())
449
	}
450
	// Output:
451
	// violation: Значение не должно быть пустым.
452
}
453
454
func ExampleValidator_Validate_translationsByContextArgument() {
455
	validator, err := validation.NewValidator(
456
		validation.Translations(russian.Messages),
457
	)
458
	if err != nil {
459
		log.Fatal(err)
460
	}
461
462
	s := ""
463
	ctx := languagepkg.WithContext(context.Background(), language.Russian)
464
	err = validator.Validate(
465
		validation.Context(ctx),
466
		validation.String(&s, it.IsNotBlank()),
467
	)
468
469
	violations := err.(validation.ViolationList)
470
	for _, violation := range violations {
471
		fmt.Println(violation.Error())
472
	}
473
	// Output:
474
	// violation: Значение не должно быть пустым.
475
}
476
477
func ExampleValidator_Validate_translationsByContextValidator() {
478
	validator, err := validation.NewValidator(
479
		validation.Translations(russian.Messages),
480
	)
481
	if err != nil {
482
		log.Fatal(err)
483
	}
484
	ctx := languagepkg.WithContext(context.Background(), language.Russian)
485
	validator = validator.WithContext(ctx)
486
487
	s := ""
488
	err = validator.ValidateString(&s, it.IsNotBlank())
489
490
	violations := err.(validation.ViolationList)
491
	for _, violation := range violations {
492
		fmt.Println(violation.Error())
493
	}
494
	// Output:
495
	// violation: Значение не должно быть пустым.
496
}
497
498
func ExampleValidator_Validate_customizingErrorMessage() {
499
	s := ""
500
501
	err := validator.ValidateString(&s, it.IsNotBlank().Message("this value is required"))
502
503
	violations := err.(validation.ViolationList)
504
	for _, violation := range violations {
505
		fmt.Println(violation.Error())
506
	}
507
	// Output:
508
	// violation: this value is required
509
}
510
511
func ExampleValidator_Validate_translationForCustomMessage() {
512
	const customMessage = "tags should contain more than {{ limit }} element(s)"
513
	validator, err := validation.NewValidator(
514
		validation.Translations(map[language.Tag]map[string]catalog.Message{
515
			language.Russian: {
516
				customMessage: plural.Selectf(1, "",
517
					plural.One, "теги должны содержать {{ limit }} элемент и более",
518
					plural.Few, "теги должны содержать более {{ limit }} элемента",
519
					plural.Other, "теги должны содержать более {{ limit }} элементов"),
520
			},
521
		}),
522
	)
523
	if err != nil {
524
		log.Fatal(err)
525
	}
526
527
	var tags []string
528
	err = validator.Validate(
529
		validation.Language(language.Russian),
530
		validation.Iterable(tags, it.HasMinCount(1).MinMessage(customMessage)),
531
	)
532
533
	violations := err.(validation.ViolationList)
534
	for _, violation := range violations {
535
		fmt.Println(violation.Error())
536
	}
537
	// Output:
538
	// violation: теги должны содержать 1 элемент и более
539
}
540