-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvalidation.go
60 lines (51 loc) · 1.91 KB
/
validation.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
// Copyright 2021 Igor Lazarev. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
// Package validation provides tools for data validation.
// It is designed to create complex validation rules with abilities to hook into the validation process.
package validation
import (
"context"
)
const DefaultGroup = "default"
// Validatable is interface for creating validatable types on the client side.
// By using it you can build complex validation rules on a set of objects used in other objects.
//
// Example
//
// type Book struct {
// Title string
// Author string
// Keywords []string
// }
//
// func (b Book) Validate(ctx context.Context, validator *validation.Validator) error {
// return validator.Validate(
// ctx,
// validation.StringProperty("title", &b.Title, it.IsNotBlank()),
// validation.StringProperty("author", &b.Author, it.IsNotBlank()),
// validation.CountableProperty("keywords", len(b.Keywords), it.HasCountBetween(1, 10)),
// validation.EachStringProperty("keywords", b.Keywords, it.IsNotBlank()),
// )
// }
type Validatable interface {
Validate(ctx context.Context, validator *Validator) error
}
// ValidatableFunc is a functional adapter for the [Validatable] interface.
type ValidatableFunc func(ctx context.Context, validator *Validator) error
// Validate runs validation process on function.
func (f ValidatableFunc) Validate(ctx context.Context, validator *Validator) error {
return f(ctx, validator)
}
// Filter is used for processing the list of errors to return a single [ViolationList].
// If there is at least one non-violation error it will return it instead.
func Filter(violations ...error) error {
list := &ViolationList{}
for _, violation := range violations {
err := list.AppendFromError(violation)
if err != nil {
return err
}
}
return list.AsError()
}