-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
validation.go
63 lines (53 loc) · 1.49 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
61
62
63
package validate
import (
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/models"
)
// Validatable defines which models can be validated against context
type Validatable interface {
Validate(user *models.User, services *app.Services) *Result
IsAuthorized(user *models.User, services *app.Services) bool
}
// ErrorItem holds a reference to something that went wrong
type ErrorItem struct {
Field string `json:"field,omitempty"`
Message string `json:"message"`
}
// Result is returned after each validation
type Result struct {
Ok bool
Authorized bool
Err error
Errors []ErrorItem
}
//AddFieldFailure add failure message to specific field
func (r *Result) AddFieldFailure(field string, messages ...string) {
if r.Errors == nil {
r.Errors = make([]ErrorItem, 0)
}
for _, message := range messages {
r.Errors = append(r.Errors, ErrorItem{
Field: field,
Message: message,
})
r.Ok = false
}
}
// Success returns a successful validation
func Success() *Result {
return &Result{Ok: true, Authorized: true}
}
// Failed returns a failed validation result
func Failed(messages ...string) *Result {
r := &Result{Ok: false, Authorized: true}
r.AddFieldFailure("", messages...)
return r
}
// Error returns a failed validation result
func Error(err error) *Result {
return &Result{Ok: false, Authorized: true, Err: err}
}
// Unauthorized returns an unauthorized validation result
func Unauthorized() *Result {
return &Result{Ok: false, Authorized: false}
}