-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate.go
More file actions
351 lines (305 loc) · 10.5 KB
/
validate.go
File metadata and controls
351 lines (305 loc) · 10.5 KB
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
package rigging
import (
"fmt"
"reflect"
"strconv"
"strings"
)
// validateField validates a single field value against tag-based constraints.
// It checks required, min, max, and oneof constraints based on the field's type.
// Returns a slice of FieldError for any validation failures.
func validateField(fieldValue reflect.Value, fieldPath string, tags tagConfig) []FieldError {
return validateFieldWithPresence(fieldValue, fieldPath, tags, nil)
}
// validateFieldWithPresence validates a single field with optional presence metadata.
// When presentFields is provided, required checks use field presence rather than non-zero values.
func validateFieldWithPresence(fieldValue reflect.Value, fieldPath string, tags tagConfig, presentFields map[string]bool) []FieldError {
var errors []FieldError
fieldPresent := presentFields != nil && presentFields[fieldPath]
// Check required constraint
if tags.required {
if presentFields != nil {
if !fieldPresent {
errors = append(errors, FieldError{
FieldPath: fieldPath,
Code: ErrCodeRequired,
Message: "field is required but not provided",
})
return errors
}
} else if isZeroValue(fieldValue) {
errors = append(errors, FieldError{
FieldPath: fieldPath,
Code: ErrCodeRequired,
Message: "field is required but not provided",
})
// If required and zero, skip other validations
return errors
}
}
// Skip other validations if value is zero (for non-required fields)
// With presence metadata, validate zero values when the field is present.
// Without presence metadata, preserve legacy behavior for non-required fields.
if isZeroValue(fieldValue) && ((presentFields != nil && !fieldPresent) || (presentFields == nil && !tags.required)) {
return errors
}
// Validate min/max constraints based on type
switch fieldValue.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
errors = append(errors, validateIntMinMax(fieldValue, fieldPath, tags)...)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
errors = append(errors, validateUintMinMax(fieldValue, fieldPath, tags)...)
case reflect.Float32, reflect.Float64:
errors = append(errors, validateFloatMinMax(fieldValue, fieldPath, tags)...)
case reflect.String:
errors = append(errors, validateStringMinMax(fieldValue, fieldPath, tags)...)
}
// Validate oneof constraint
if len(tags.oneof) > 0 {
errors = append(errors, validateOneof(fieldValue, fieldPath, tags)...)
}
return errors
}
// validateStruct walks a struct and validates all fields according to their tags.
// It recursively validates nested structs.
// Returns a slice of all FieldError encountered.
func validateStruct(cfg reflect.Value) []FieldError {
return validateStructWithPresence(cfg, nil)
}
// validateStructWithPresence validates a struct with optional field presence metadata.
func validateStructWithPresence(cfg reflect.Value, presentFields map[string]bool) []FieldError {
return validateStructRecursive(cfg, "", presentFields)
}
// validateStructRecursive is the internal recursive implementation of validateStruct.
func validateStructRecursive(cfg reflect.Value, parentFieldPath string, presentFields map[string]bool) []FieldError {
var fieldErrors []FieldError
validateFieldFn := func(value reflect.Value, path string, tags tagConfig) []FieldError {
if presentFields == nil {
return validateField(value, path, tags)
}
return validateFieldWithPresence(value, path, tags, presentFields)
}
// Dereference pointer if needed
if cfg.Kind() == reflect.Ptr {
if cfg.IsNil() {
return fieldErrors
}
cfg = cfg.Elem()
}
// Ensure we have a struct
if cfg.Kind() != reflect.Struct {
return fieldErrors
}
cfgType := cfg.Type()
// Walk through exported fields using cached metadata.
for _, meta := range getStructFieldMeta(cfgType) {
field := meta.field
fieldValue := cfg.Field(meta.index)
// Build field path
fieldPath := field.Name
if parentFieldPath != "" {
fieldPath = parentFieldPath + "." + field.Name
}
tagCfg := meta.tagCfg
// Handle Optional[T] types.
if isOptionalType(fieldValue.Type()) {
setField := fieldValue.Field(1) // Set field
if !setField.Bool() {
if tagCfg.required && (presentFields == nil || !presentFields[fieldPath]) {
fieldErrors = append(fieldErrors, FieldError{
FieldPath: fieldPath,
Code: ErrCodeRequired,
Message: "field is required but not provided",
})
}
continue
}
valueField := fieldValue.Field(0) // Value field
errors := validateFieldFn(valueField, fieldPath, tagCfg)
fieldErrors = append(fieldErrors, errors...)
continue
}
// Handle nested structs recursively
if fieldValue.Kind() == reflect.Struct {
// Skip time.Time and time.Duration (they're structs but should be treated as primitives)
if fieldValue.Type().PkgPath() == "time" {
// Validate as a regular field
errors := validateFieldFn(fieldValue, fieldPath, tagCfg)
fieldErrors = append(fieldErrors, errors...)
continue
}
// Recursively validate nested struct
nestedErrors := validateStructRecursive(fieldValue, fieldPath, presentFields)
fieldErrors = append(fieldErrors, nestedErrors...)
continue
}
// Validate the field
errors := validateFieldFn(fieldValue, fieldPath, tagCfg)
fieldErrors = append(fieldErrors, errors...)
}
return fieldErrors
}
// isZeroValue checks if a reflect.Value is the zero value for its type.
func isZeroValue(v reflect.Value) bool {
switch v.Kind() {
case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
return v.Len() == 0
case reflect.Bool:
return !v.Bool()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int() == 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return v.Uint() == 0
case reflect.Float32, reflect.Float64:
return v.Float() == 0
case reflect.Interface, reflect.Ptr:
return v.IsNil()
case reflect.Struct:
// For structs, check if all fields are zero
return v.IsZero()
default:
return v.IsZero()
}
}
// validateIntMinMax validates min/max constraints for signed integer types.
func validateIntMinMax(fieldValue reflect.Value, fieldPath string, tags tagConfig) []FieldError {
var errors []FieldError
value := fieldValue.Int()
if tags.min != "" {
minVal, err := strconv.ParseInt(tags.min, 10, 64)
if err == nil && value < minVal {
errors = append(errors, FieldError{
FieldPath: fieldPath,
Code: ErrCodeMin,
Message: fmt.Sprintf("value %d is below minimum %d", value, minVal),
})
}
}
if tags.max != "" {
maxVal, err := strconv.ParseInt(tags.max, 10, 64)
if err == nil && value > maxVal {
errors = append(errors, FieldError{
FieldPath: fieldPath,
Code: ErrCodeMax,
Message: fmt.Sprintf("value %d exceeds maximum %d", value, maxVal),
})
}
}
return errors
}
// validateUintMinMax validates min/max constraints for unsigned integer types.
func validateUintMinMax(fieldValue reflect.Value, fieldPath string, tags tagConfig) []FieldError {
var errors []FieldError
value := fieldValue.Uint()
if tags.min != "" {
minVal, err := strconv.ParseUint(tags.min, 10, 64)
if err == nil && value < minVal {
errors = append(errors, FieldError{
FieldPath: fieldPath,
Code: ErrCodeMin,
Message: fmt.Sprintf("value %d is below minimum %d", value, minVal),
})
}
}
if tags.max != "" {
maxVal, err := strconv.ParseUint(tags.max, 10, 64)
if err == nil && value > maxVal {
errors = append(errors, FieldError{
FieldPath: fieldPath,
Code: ErrCodeMax,
Message: fmt.Sprintf("value %d exceeds maximum %d", value, maxVal),
})
}
}
return errors
}
// validateFloatMinMax validates min/max constraints for floating-point types.
func validateFloatMinMax(fieldValue reflect.Value, fieldPath string, tags tagConfig) []FieldError {
var errors []FieldError
value := fieldValue.Float()
if tags.min != "" {
minVal, err := strconv.ParseFloat(tags.min, 64)
if err == nil && value < minVal {
errors = append(errors, FieldError{
FieldPath: fieldPath,
Code: ErrCodeMin,
Message: fmt.Sprintf("value %g is below minimum %g", value, minVal),
})
}
}
if tags.max != "" {
maxVal, err := strconv.ParseFloat(tags.max, 64)
if err == nil && value > maxVal {
errors = append(errors, FieldError{
FieldPath: fieldPath,
Code: ErrCodeMax,
Message: fmt.Sprintf("value %g exceeds maximum %g", value, maxVal),
})
}
}
return errors
}
// validateStringMinMax validates min/max constraints for string length.
func validateStringMinMax(fieldValue reflect.Value, fieldPath string, tags tagConfig) []FieldError {
var errors []FieldError
value := fieldValue.String()
length := len(value)
if tags.min != "" {
minLen, err := strconv.Atoi(tags.min)
if err == nil && length < minLen {
errors = append(errors, FieldError{
FieldPath: fieldPath,
Code: ErrCodeMin,
Message: fmt.Sprintf("string length %d is below minimum %d", length, minLen),
})
}
}
if tags.max != "" {
maxLen, err := strconv.Atoi(tags.max)
if err == nil && length > maxLen {
errors = append(errors, FieldError{
FieldPath: fieldPath,
Code: ErrCodeMax,
Message: fmt.Sprintf("string length %d exceeds maximum %d", length, maxLen),
})
}
}
return errors
}
// validateOneof validates that a field value is one of the allowed options.
func validateOneof(fieldValue reflect.Value, fieldPath string, tags tagConfig) []FieldError {
var errors []FieldError
// Convert field value to string for comparison
var valueStr string
switch fieldValue.Kind() {
case reflect.String:
valueStr = fieldValue.String()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
valueStr = strconv.FormatInt(fieldValue.Int(), 10)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
valueStr = strconv.FormatUint(fieldValue.Uint(), 10)
case reflect.Float32, reflect.Float64:
valueStr = strconv.FormatFloat(fieldValue.Float(), 'f', -1, 64)
case reflect.Bool:
valueStr = strconv.FormatBool(fieldValue.Bool())
default:
// For unsupported types, skip oneof validation
return errors
}
// Check if value is in the allowed set
found := false
for _, allowed := range tags.oneof {
if valueStr == allowed {
found = true
break
}
}
if !found {
errors = append(errors, FieldError{
FieldPath: fieldPath,
Code: ErrCodeOneOf,
Message: fmt.Sprintf("value %q must be one of: %s", valueStr, strings.Join(tags.oneof, ", ")),
})
}
return errors
}