This repository was archived by the owner on Jul 22, 2026. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathstructcheck.go
More file actions
417 lines (374 loc) · 10.9 KB
/
Copy pathstructcheck.go
File metadata and controls
417 lines (374 loc) · 10.9 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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
// Package godantic is written by Ismael GraHms
package godantic
import (
"fmt"
"reflect"
"regexp"
"strings"
"time"
)
func getValueOf(val interface{}) reflect.Value {
return reflect.ValueOf(val)
}
func isPtr(value reflect.Value) bool {
return value.Kind() == reflect.Ptr
}
func isStruct(value reflect.Value) bool {
kind := value.Kind()
return kind == reflect.Struct || (kind == reflect.Ptr && value.Elem().Kind() == reflect.Struct)
}
func isString(value reflect.Value) bool {
return value.Kind() == reflect.String
}
func isTime(value reflect.Value) bool {
return value.Type().ConvertibleTo(TimeType)
}
func isList(value reflect.Value) bool {
return value.Kind() == reflect.Slice || value.Kind() == reflect.Array
}
var TimeType = reflect.TypeOf(time.Time{})
func (g *Validate) InspectStruct(val interface{}) error {
enumMap := extractEnumValues(getValueOf(val), "")
return g.inspect(val, "", 0, reflect.StructField{}, enumMap)
}
func (g *Validate) inspect(val interface{}, tree string, i int, f reflect.StructField, enumMap map[string]string) error {
v := getValueOf(val)
switch {
case isPtr(v):
return g.inspect(v.Elem().Interface(), tree, i, f, enumMap)
case isTime(v):
return g.checkTime(v, tree)
case isStruct(v):
return g.checkStruct(val, v, tree, enumMap)
case isString(v):
return g.checkString(v, tree, i, f)
case isList(v):
return g.checkList(v, tree, enumMap)
default:
return nil
}
}
func getFormatRegex(formatTag string) string {
switch formatTag {
case "email":
return `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`
case "url":
return `^(http|https)://[a-zA-Z0-9./?=_%-&]+$`
case "date":
return `^\d{4}-\d{2}-\d{2}$`
case "time":
return `^([01]\d|2[0-3]):([0-5]\d):([0-5]\d)$`
case "uuid":
return `^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`
case "ip":
return `^(\d{1,3}\.){3}\d{1,3}$`
case "credit_card":
return `^\d{4}-\d{4}-\d{4}-\d{4}$`
case "postal_code":
return `^[a-zA-Z0-9]+$`
case "phone":
return `^\+[1-9]\d{1,14}$`
case "ssn":
return `^\d{3}-\d{2}-\d{4}$`
case "credit_card_expiry":
return `^(0[1-9]|1[0-2])\/(20\d{2}|2[1-9]\d{1})$`
case "latitude":
return `^(-?([0-8]?[0-9]\.\d+|90(\.0+)?))$`
case "longitude":
return `^(-?((1?[0-7]?|[0-9]?)[0-9]\.\d+|180(\.0+)?))$`
case "hex_color":
return `^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$`
case "mac_address":
return `^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$`
case "mz-msisdn":
return `^258\d{9}$`
case "mz-nuit":
return `^\d{9}$`
case "mz-bi":
return `^\d{12}[A-Z]$`
default:
return ""
}
}
func (g *Validate) formatValidation(f reflect.StructField, v reflect.Value, tree string) error {
tag := f.Tag.Get("format")
if tag == "" {
return nil
}
if v.Kind() == reflect.Ptr {
if v.IsNil() {
return nil
}
v = v.Elem()
}
fieldValue := v.String()
formatRegex := getFormatRegex(tag)
if err := matchRegexPattern(formatRegex, fieldValue, f, tree); err != nil {
return &Error{
ErrType: fmt.Sprintf("INVALID_%s_ERR", strings.ToUpper(tag)),
Path: fieldName(f, tree),
Message: fmt.Sprintf("error on field <%s>. the given value '%s' is not a valid %s", fieldName(f, tree), fieldValue, tag),
}
}
return nil
}
func matchRegexPattern(regexpPattern, fieldValue string, f reflect.StructField, tree string) error {
// Compile the regular expression pattern
regexpPatternCompiled, err := regexp.Compile(regexpPattern)
if err != nil {
return err // Handle error
}
// Check if the field's value matches the regular expression pattern
if !regexpPatternCompiled.MatchString(fieldValue) {
return &Error{
ErrType: "INVALID_PATTERN_ERR",
Path: fieldName(f, tree),
Message: fmt.Sprintf("The field <%s> value '%s' does not match the required pattern: %s", fieldName(f, tree), fieldValue, regexpPattern),
}
}
return nil
}
func (g *Validate) regexPattern(f reflect.StructField, v reflect.Value, tree string) error {
regexpPattern := f.Tag.Get("regex")
if regexpPattern == "" {
return nil
}
if v.Kind() == reflect.Ptr {
if v.IsNil() {
return nil
}
v = v.Elem()
}
fieldValue := v.String()
// Compile the regular expression pattern
return matchRegexPattern(regexpPattern, fieldValue, f, tree)
}
func (g *Validate) checkTime(v reflect.Value, tree string) error {
timeValue := v.Interface().(time.Time)
if timeValue.IsZero() {
return &Error{
ErrType: "INVALID_TIME_ERR",
Path: tree,
Message: "The field <" + tree + "> cannot have an invalid time value",
}
}
return nil
}
func (g *Validate) checkString(v reflect.Value, tree string, _ int, f reflect.StructField) error {
passTag := f.Tag.Get("pass-empty")
if passTag == "true" {
return nil
}
s := strings.TrimSpace(v.String())
if len(s) < 1 {
return &Error{
ErrType: "EMPTY_STRING_ERR",
Path: tree,
Message: "The field <" + tree + "> cannot be an empty string",
}
}
return nil
}
func (g *Validate) checkList(v reflect.Value, tree string, enumMap map[string]string) error {
min := 1
if g.IgnoreMinLen {
min = 0
}
isLesserThanMinLength := v.Len() < min
if isLesserThanMinLength {
return &Error{
ErrType: "EMPTY_LIST_ERR",
Path: tree,
Message: fmt.Sprintf("Field <%s> must be with at least one value.", tree),
}
}
for i := 0; i < v.Len(); i++ {
elem := v.Index(i)
elemPath := fmt.Sprintf("%s[%d]", tree, i)
err := g.inspect(elem.Interface(), elemPath, i, reflect.StructField{}, enumMap)
if err != nil {
return err
}
if cv, ok := resolveInterface[ValidationPlugin](elem); ok {
if err := cv.Validate(); err != nil {
return err
}
}
if df, ok := resolveInterface[DynamicFieldsValidator](elem); ok {
if err := validateDynamicFields(df.GetValue(), df.GetAttribute(), df.GetValueType(), elemPath); err != nil {
return err
}
}
}
return nil
}
func (g *Validate) checkStruct(val interface{}, v reflect.Value, tree string, enumMao map[string]string) error {
t := v.Type()
if err := g.validateInterfaceHooks(val, tree); err != nil {
return err
}
for i := 0; i < t.NumField(); i++ {
if isTime(v.Field(i)) {
f := t.Field(i)
// Only reject a zero time if the field is explicitly required.
if isFieldRequired(f) {
if err := g.checkTime(v.Field(i), fieldName(f, tree)); err != nil {
return err
}
}
continue
}
err := g.checkField(val, v, t, tree, i, enumMao)
if err != nil {
return err
}
}
return nil
}
func (g *Validate) checkField(val interface{}, v reflect.Value, t reflect.Type, tree string, i int, enumMap map[string]string) error {
f := t.Field(i)
if f.PkgPath != "" {
// Field is unexported, handle it gracefully
return nil
}
enums := f.Tag.Get("enum")
if len(enums) == 0 {
enums = f.Tag.Get("enums")
}
valField := v.Field(i)
if tag := f.Tag.Get("binding"); tag == "ignore" && !reflect.DeepEqual(valField.Interface(), reflect.Zero(f.Type).Interface()) {
return &Error{
ErrType: "INVALID_FIELD_ERR",
Path: fieldName(f, tree),
Message: fmt.Sprintf("Invalid field <%s>", fieldName(f, tree)),
}
}
switch {
case f.Type.Kind() == reflect.Slice || f.Type.Kind() == reflect.Array:
// Empty slice: fail only when the field is required.
if valField.Len() == 0 {
if !g.IgnoreRequired && isFieldRequired(f) {
return RequiredFieldError(f, tree)
}
break
}
// Non-empty: recurse into elements — this was the missing step for plain (non-pointer) slice fields.
if err := g.checkList(valField, fieldName(f, tree), enumMap); err != nil {
return err
}
case f.Type.Kind() == reflect.Ptr && !valField.IsNil():
// Handle pointer fields
if err := g.inspect(valField.Interface(), fieldName(f, tree), i, f, enumMap); err != nil {
return err
}
case f.Type.Kind() == reflect.Struct:
// Handle non-pointer struct fields
if err := g.checkStruct(val, valField, fieldName(f, tree), enumMap); err != nil {
return err
}
case f.Type.Kind() != reflect.Ptr:
isZero := reflect.DeepEqual(valField.Interface(), reflect.Zero(f.Type).Interface())
if !g.IgnoreRequired && isFieldRequired(f) && isZero {
return RequiredFieldError(f, tree)
}
// Whitespace-only required strings must also be rejected, consistent with *string behaviour.
if !g.IgnoreRequired && f.Type.Kind() == reflect.String && isFieldRequired(f) && !isZero {
if err := g.checkString(valField, fieldName(f, tree), i, f); err != nil {
return err
}
}
case !g.IgnoreRequired:
if isFieldRequired(f) {
if f.Type.Kind() == reflect.Ptr && valField.IsNil() {
return RequiredFieldError(f, tree)
}
}
}
if err := g.validateCondition(f, valField, tree, enumMap); err != nil {
return err
}
if err := g.checkMinMax(f, valField, tree); err != nil {
return err
}
if err := g.checkNumericConstraints(f, valField, tree); err != nil {
return err
}
if err := g.checkDecimalConstraints(f, valField, tree); err != nil {
return err
}
if err := g.regexPattern(f, valField, tree); err != nil {
return err
}
if err := g.formatValidation(f, valField, tree); err != nil {
return err
}
if err := g.validateWithCustomTag(valField.Interface(), f, fieldName(f, tree)); err != nil {
return err
}
// Check for enum validation tags.
if len(enums) > 0 {
enumValues := strings.Split(strings.TrimSpace(enums), ",")
err := g.strEnums(f, valField, tree, enumValues)
if err != nil {
return err
}
}
if cv, ok := resolveInterface[ValidationPlugin](valField); ok {
if err := cv.Validate(); err != nil {
return err
}
}
if df, ok := resolveInterface[DynamicFieldsValidator](valField); ok {
if err := validateDynamicFields(df.GetValue(), df.GetAttribute(), df.GetValueType(), fieldName(f, tree)); err != nil {
return err
}
}
return nil
}
func (g *Validate) strEnums(f reflect.StructField, val reflect.Value, tree string, allowedValues []string) error {
if val.Kind() == reflect.Ptr {
if val.IsNil() {
return nil
}
val = val.Elem()
}
fieldValue := val.String()
// Convert the allowedValues slice to a map for faster searching.
allowedMap := make(map[string]bool, len(allowedValues))
for _, allowedValue := range allowedValues {
allowedMap[allowedValue] = true
}
if _, ok := allowedMap[fieldValue]; !ok {
return &Error{
ErrType: "INVALID_ENUM_ERR",
Path: fieldName(f, tree),
Message: fmt.Sprintf("The field <%s> must have one of the following values: %s, '%s' was given",
fieldName(f, tree), strings.Join(allowedValues, ", "), val.String()),
}
}
return nil
}
func fieldName(f reflect.StructField, tree string) string {
var name string
if f.Tag != "" {
jsonTag := strings.Split(f.Tag.Get("json"), ",")[0]
name = jsonTag
if len(tree) > 0 {
name = tree + "." + jsonTag
}
}
return name
}
func isFieldRequired(f reflect.StructField) bool {
if f.Tag.Get("binding") == "required" {
return true
}
return false
}
func RequiredFieldError(field reflect.StructField, tree string) error {
return &Error{
ErrType: "REQUIRED_FIELD_ERR",
Path: fieldName(field, tree),
Message: fmt.Sprintf("The field <%s> is required", fieldName(field, tree)),
}
}