-
Notifications
You must be signed in to change notification settings - Fork 1
/
field.go
60 lines (50 loc) · 985 Bytes
/
field.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
package forms
import (
"errors"
"fmt"
)
type FormatterFunc func(string) string
type Field struct {
Name string
formatters []FormatterFunc
loader LoaderFunc
validators []ValidatorFunc
required bool
empty interface{}
}
func (f *Field) Validate(rawValue string) (interface{}, error) {
if rawValue == "" {
if f.required {
return nil, errors.New(fmt.Sprintf("%s is required", f.Name))
} else {
return f.empty, nil
}
}
// format raw input
rawValue = f.format(rawValue)
// deserialize
value, err := f.loader(rawValue)
if err != nil {
return nil, err
}
// validate
err = f.validate(value)
if err != nil {
return nil, err
}
return value, nil
}
func (f *Field) format(rawValue string) string {
for _, f := range f.formatters {
rawValue = f(rawValue)
}
return rawValue
}
func (f *Field) validate(value interface{}) error {
for _, v := range f.validators {
if err := v(value); err != nil {
return err
}
}
return nil
}