forked from volatiletech/authboss
-
Notifications
You must be signed in to change notification settings - Fork 0
/
validation.go
109 lines (90 loc) · 2.31 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
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
package authboss
import (
"bytes"
"fmt"
"net/http"
)
const (
// ConfirmPrefix is prepended to names of confirm fields.
ConfirmPrefix = "confirm_"
)
// Validator is anything that can validate a string and provide a list of errors
// and describe its set of rules.
type Validator interface {
Field() string
Errors(in string) ErrorList
Rules() []string
}
// ErrorList is simply a slice of errors with helpers.
type ErrorList []error
// Error satisfies the error interface.
func (e ErrorList) Error() string {
b := &bytes.Buffer{}
first := true
for _, err := range e {
if first {
first = false
} else {
b.WriteString(", ")
}
b.WriteString(err.Error())
}
return b.String()
}
// Map groups errors by their field name
func (e ErrorList) Map() map[string][]string {
m := make(map[string][]string)
for _, err := range e {
fieldErr, ok := err.(FieldError)
if !ok {
m[""] = append(m[""], err.Error())
} else {
m[fieldErr.Name] = append(m[fieldErr.Name], fieldErr.Err.Error())
}
}
return m
}
// FieldError represents an error that occurs during validation and is always
// attached to field on a form.
type FieldError struct {
Name string
Err error
}
func (f FieldError) Error() string {
return fmt.Sprintf("%s: %v", f.Name, f.Err)
}
// Validate validates a request using the given ruleset.
func Validate(r *http.Request, ruleset []Validator, confirmFields ...string) ErrorList {
errList := make(ErrorList, 0)
for _, validator := range ruleset {
field := validator.Field()
val := r.FormValue(field)
if errs := validator.Errors(val); len(errs) > 0 {
errList = append(errList, errs...)
}
}
for i := 0; i < len(confirmFields)-1; i += 2 {
main := r.FormValue(confirmFields[i])
if len(main) == 0 {
continue
}
confirm := r.FormValue(confirmFields[i+1])
if len(confirm) == 0 || main != confirm {
errList = append(errList, FieldError{confirmFields[i+1], fmt.Errorf("Does not match %s", confirmFields[i])})
}
}
return errList
}
// FilterValidators returns a subset of registered validators
func FilterValidators(validators []Validator, fields ...string) []Validator {
var arr []Validator
for _, validator := range validators {
fieldName := validator.Field()
for _, field := range fields {
if fieldName == field {
arr = append(arr, validator)
}
}
}
return arr
}