|
1
|
|
|
// Copyright 2021 Igor Lazarev. All rights reserved. |
|
2
|
|
|
// Use of this source code is governed by a MIT-style |
|
3
|
|
|
// license that can be found in the LICENSE file. |
|
4
|
|
|
|
|
5
|
|
|
// Package validation provides tools for data validation. |
|
6
|
|
|
// It is designed to create complex validation rules with abilities to hook into the validation process. |
|
7
|
|
|
package validation |
|
8
|
|
|
|
|
9
|
|
|
import ( |
|
10
|
|
|
"context" |
|
11
|
|
|
) |
|
12
|
|
|
|
|
13
|
|
|
// Validatable is interface for creating validatable types on the client side. |
|
14
|
|
|
// By using it you can build complex validation rules on a set of objects used in other objects. |
|
15
|
|
|
// |
|
16
|
|
|
// Example |
|
17
|
|
|
// type Book struct { |
|
18
|
|
|
// Title string |
|
19
|
|
|
// Author string |
|
20
|
|
|
// Keywords []string |
|
21
|
|
|
// } |
|
22
|
|
|
// |
|
23
|
|
|
// func (b Book) Validate(ctx context.Context, validator *validation.Validator) error { |
|
24
|
|
|
// return validator.Validate( |
|
25
|
|
|
// ctx, |
|
26
|
|
|
// validation.StringProperty("title", &b.Title, it.IsNotBlank()), |
|
27
|
|
|
// validation.StringProperty("author", &b.Author, it.IsNotBlank()), |
|
28
|
|
|
// validation.CountableProperty("keywords", len(b.Keywords), it.HasCountBetween(1, 10)), |
|
29
|
|
|
// validation.EachStringProperty("keywords", b.Keywords, it.IsNotBlank()), |
|
30
|
|
|
// ) |
|
31
|
|
|
// } |
|
32
|
|
|
type Validatable interface { |
|
33
|
|
|
Validate(ctx context.Context, validator *Validator) error |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
// Filter is used for processing the list of errors to return a single ViolationList. |
|
37
|
|
|
// If there is at least one non-violation error it will return it instead. |
|
38
|
|
|
func Filter(violations ...error) error { |
|
39
|
|
|
list := &ViolationList{} |
|
40
|
|
|
|
|
41
|
|
|
for _, violation := range violations { |
|
42
|
|
|
err := list.AppendFromError(violation) |
|
43
|
1 |
|
if err != nil { |
|
44
|
|
|
return err |
|
45
|
1 |
|
} |
|
46
|
1 |
|
} |
|
47
|
1 |
|
|
|
48
|
1 |
|
return list.AsError() |
|
49
|
|
|
} |
|
50
|
|
|
|