-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfield_context.go
232 lines (196 loc) · 5.66 KB
/
field_context.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
package validator
import (
"reflect"
"strings"
"golang.org/x/exp/slices"
)
type fieldContext struct {
filters []*fieldValueFilter
validators []*fieldValueValidator
fieldName string
fieldKind reflect.Kind
fieldLabel string
fieldMessageTemplate string
hasLabel bool
hasMessagTemplate bool
triggers []string
flags []ValidationFlag
zeroValue reflect.Value
}
func (fc *fieldContext) isFlagSet(flag ValidationFlag) bool {
return slices.Contains(fc.flags, flag)
}
func (fc *fieldContext) isZero(v reflect.Value) bool {
return fc.zeroValue.Equal(v)
}
func (fc *fieldContext) activate(trigger string) bool {
if !slices.Contains(fc.triggers, trigger) {
return slices.Contains(fc.triggers, "all")
}
return true
}
func (fc *fieldContext) apply(structValue reflect.Value, opts *ValidationOptions) []FieldError {
field := structValue.FieldByName(fc.fieldName)
value := field.Addr().Elem()
ispointer := value.Kind() == reflect.Ptr
var isnull bool = false
var errorList []FieldError
if ispointer {
isnull = value.IsNil()
}
if fc.isFlagSet(AllowZero) {
if ispointer {
if value.IsZero() || fc.isZero(value.Elem()) {
return nil
}
} else if fc.isZero(value) {
return nil
}
}
for _, validator := range fc.validators {
ctx := ValidationContext{
IsPointer: ispointer,
IsNull: isnull,
Options: opts,
Args: validator.args,
value: value,
valueKind: fc.fieldKind,
}
if !validator.fn(&ctx) {
fe := FieldError{Field: fc.fieldLabel}
if fc.hasMessagTemplate {
fe.Message = fc.fieldMessageTemplate
} else {
if len(ctx.ErrorMessage) > 0 {
fe.Message = ctx.ErrorMessage
} else {
fe.Message = fc.fieldLabel + ": field validation failed"
if opts.ExposeValidatorNames {
fe.Message += " using function " + validator.name
}
}
}
errorList = append(errorList, fe)
if opts.StopOnFirstError {
return errorList
}
}
}
for _, filter := range fc.filters {
ctx := ValidationContext{
IsPointer: ispointer,
IsNull: isnull,
Options: opts,
Args: filter.args,
value: value,
valueKind: fc.fieldKind,
}
newValue := filter.fn(&ctx)
value.Set(newValue)
}
return errorList
}
func mustParseField(field reflect.StructField, opts *ValidationOptions) (ctx *fieldContext) {
// skip over unexported fields
if field.Name[0] >= 'a' && field.Name[0] <= 'z' {
return
}
flagTagValues, hasFlags := field.Tag.Lookup(opts.FlagTagName)
filterTagValues, filters := field.Tag.Lookup(opts.FilterTagName)
triggerTagValues, hasTriggers := field.Tag.Lookup(opts.TriggerTagName)
validatorTagValues, validators := field.Tag.Lookup(opts.ValidatorTagName)
messageTemplate, hasMsgTemplate := field.Tag.Lookup(opts.MessageTagName)
label, hasLabel := field.Tag.Lookup(opts.LabelTagName)
if !filters && !validators {
return
}
var zeroValue reflect.Value
if field.Type.Kind() == reflect.Ptr {
zeroValue = reflect.Zero(field.Type.Elem())
} else {
zeroValue = reflect.Zero(field.Type)
}
fc := fieldContext{
validators: make([]*fieldValueValidator, 0),
filters: make([]*fieldValueFilter, 0),
hasLabel: hasLabel,
hasMessagTemplate: hasMsgTemplate,
fieldKind: field.Type.Kind(),
zeroValue: zeroValue,
}
if hasTriggers {
triggers := strings.Split(triggerTagValues, ",")
fc.triggers = append(fc.triggers, triggers...)
} else {
fc.triggers = append(fc.triggers, "all")
}
fc.fieldName = field.Name
// resolve actual contained type
kinds := []reflect.Kind{reflect.Array, reflect.Map, reflect.Slice, reflect.Pointer}
if slices.Contains(kinds, field.Type.Kind()) {
fc.fieldKind = field.Type.Elem().Kind()
}
if hasLabel {
fc.fieldLabel = label
} else {
fc.fieldLabel = field.Name
}
if hasMsgTemplate {
fc.fieldMessageTemplate = messageTemplate
}
if validators {
// split by "|"
// `validate:"required|uuidv4|v1(arg1,arg2)"`
parts := strings.Split(validatorTagValues, "|")
if len(parts) > 0 {
for _, function := range parts {
// extract
name, args := extractFunctionInformation(function)
v, ok := validatorFunctions[name]
if !ok {
panic(newValidationError("validator `" + name + "` referenced by field " + field.Name + " not found"))
}
fc.validators = append(fc.validators, &fieldValueValidator{name: name, fn: v, args: args})
}
}
}
if filters {
parts := strings.Split(filterTagValues, "|")
if len(parts) > 0 {
for _, function := range parts {
// extract
name, args := extractFunctionInformation(function)
v, ok := filterFunctions[name]
if !ok {
panic(newValidationError("filter " + name + " referenced by field " + field.Name + " not found"))
}
fc.filters = append(fc.filters, &fieldValueFilter{name: name, fn: v, args: args})
}
}
}
if hasFlags {
parts := strings.Split(flagTagValues, "|")
if len(parts) > 0 {
for _, flag := range parts {
fc.flags = append(fc.flags, ValidationFlag(strings.TrimSpace(flag)))
}
}
}
ctx = &fc
return
}
func extractFunctionInformation(funcDefinition string) (name string, args []string) {
if strings.HasSuffix(funcDefinition, "()") {
name = strings.Trim(funcDefinition, "()")
args = []string{}
} else if strings.ContainsAny(funcDefinition, "()") {
openParenthesisPosition := strings.Index(funcDefinition, "(")
closeParenthesisPosition := strings.LastIndex(funcDefinition, ")")
name = funcDefinition[0:openParenthesisPosition]
args = strings.Split(funcDefinition[openParenthesisPosition+1:closeParenthesisPosition], ",")
} else {
name = funcDefinition
args = []string{}
}
return
}