forked from volatiletech/authboss
/
validation.go
75 lines (59 loc) · 1.72 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
package defaults
import (
"fmt"
"github.com/justin-wilxite/authboss/v3"
)
// HTTPFormValidator validates HTTP post type inputs
type HTTPFormValidator struct {
Values map[string]string
Ruleset []Rules
ConfirmFields []string
}
// Validate validates a request using the given ruleset.
func (h HTTPFormValidator) Validate() []error {
var errList authboss.ErrorList
for _, rule := range h.Ruleset {
field := rule.FieldName
val := h.Values[field]
if errs := rule.Errors(val); len(errs) > 0 {
errList = append(errList, errs...)
}
}
if l := len(h.ConfirmFields); l != 0 && l%2 != 0 {
panic("HTTPFormValidator given an odd number of confirm fields")
}
for i := 0; i < len(h.ConfirmFields)-1; i += 2 {
main := h.Values[h.ConfirmFields[i]]
if len(main) == 0 {
continue
}
confirm := h.Values[h.ConfirmFields[i+1]]
if len(confirm) == 0 || main != confirm {
errList = append(errList, FieldError{h.ConfirmFields[i+1], fmt.Errorf("Does not match %s", h.ConfirmFields[i])})
}
}
return errList
}
// FieldError represents an error that occurs during validation and is always
// attached to field on a form.
type FieldError struct {
FieldName string
FieldErr error
}
// NewFieldError literally only exists because of poor name planning
// where name and err can't be exported on the struct due to the method names
func NewFieldError(name string, err error) FieldError {
return FieldError{FieldName: name, FieldErr: err}
}
// Name of the field the error is about
func (f FieldError) Name() string {
return f.FieldName
}
// Err for the field
func (f FieldError) Err() error {
return f.FieldErr
}
// Error in string form
func (f FieldError) Error() string {
return fmt.Sprintf("%s: %v", f.FieldName, f.FieldErr)
}