Repository navigation
Expand file tree
/
Copy pathvalidate.go
More file actions
224 lines (199 loc) · 5.7 KB
/
Copy pathvalidate.go
File metadata and controls
224 lines (199 loc) · 5.7 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
package validator
import (
"errors"
"fmt"
"reflect"
"strconv"
"strings"
)
// Validate takes a struct and validates values of its fields based on their tags.
func Validate(obj interface{}, options *ValidateOptions) (bool, map[string]uint64, error) {
if options == nil {
options = &ValidateOptions{} // use defaults
}
tagName := "validation"
if options.TagName != "" {
tagName = options.TagName
}
val := reflect.ValueOf(obj)
// If we received a pointer to a pointer, keep dereferencing until we hit a non‑pointer.
// This also normalizes the case where the caller passed a pointer to a struct.
for val.Kind() == reflect.Pointer {
if val.IsNil() {
return false, nil, errors.New("nil pointer supplied")
}
val = val.Elem()
}
if val.Kind() != reflect.Struct {
return false, nil, fmt.Errorf("obj is not a struct or pointer to struct, got %s", val.Kind())
}
typ := val.Type()
numField := typ.NumField()
fieldViolations := make(map[string]uint64, numField)
overallOk := true
for i := 0; i < numField; i++ {
structField := typ.Field(i)
fieldValue := val.Field(i)
// unexported fields are not validated
if !structField.IsExported() {
continue
}
// check if only specified field should be checked
if len(options.RestrictFields) > 0 && !options.RestrictFields[structField.Name] {
continue
}
// check if the field exists in options.OverwriteValues
if options.OverwriteValues != nil {
if overwriteVal, exists := options.OverwriteValues[structField.Name]; exists {
fieldValue = reflect.ValueOf(overwriteVal)
// check if fieldValue can be assigned to structField
if !fieldValue.Type().AssignableTo(structField.Type) {
overallOk = false
fieldViolations[structField.Name] = FailType
continue
}
}
}
ok, viol := ValidateField(structField, fieldValue, tagName)
if !ok {
overallOk = false
fieldViolations[structField.Name] = viol
}
}
return overallOk, fieldViolations, nil
}
// ValidateField takes a reflected struct field, its value and a tagname and validates the values against the requirements in the tag.
func ValidateField(structField reflect.StructField, fieldValue reflect.Value, tagName string) (bool, uint64) {
var violations uint64 = 0
tag := structField.Tag.Get(tagName)
isNilPointer, kind, concrete := dereferenceKind(fieldValue)
tag = strings.TrimSpace(tag)
if tag == "-" {
return true, 0
}
if tag != "" {
tokens := strings.Fields(tag)
// check req first
for _, token := range tokens {
name, _ := parseRule(token)
if name == "req" && isNilPointer {
violations += FailReq
break
}
}
// make further checks only if not nil
if !isNilPointer {
for _, token := range tokens {
name, arg := parseRule(token)
switch name {
case "email":
if kind != reflect.String {
// Wrong kind → treat as a violation (helps catch config errors)
violations += FailType
break
}
if !emailRegexp.MatchString(concrete.String()) {
violations += FailEmail
}
case "len":
if kind != reflect.String {
violations += FailType
break
}
minMax := strings.Split(arg, ",")
if minMax[0] != "" {
min, err := strconv.Atoi(minMax[0])
if err == nil {
if len(concrete.String()) < min {
violations += FailLenMin
}
}
}
if len(minMax) > 1 && minMax[1] != "" {
max, err := strconv.Atoi(minMax[1])
if err == nil {
if len(concrete.String()) > max {
violations += FailLenMax
}
}
}
case "val":
// First, make sure we are dealing with a numeric kind.
minMax := strings.Split(arg, ",")
switch kind {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if minMax[0] != "" {
min, err := strconv.ParseInt(minMax[0], 10, 64)
if err == nil {
if concrete.Int() < min {
violations += FailValMin
}
}
}
if len(minMax) > 1 && minMax[1] != "" {
max, err := strconv.ParseInt(minMax[1], 10, 64)
if err == nil {
if concrete.Int() > max {
violations += FailValMax
}
}
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
if minMax[0] != "" {
min, err := strconv.ParseUint(minMax[0], 10, 64)
if err == nil {
if concrete.Uint() < min {
violations += FailValMin
}
}
}
if len(minMax) > 1 && minMax[1] != "" {
max, err := strconv.ParseUint(minMax[1], 10, 64)
if err == nil {
if concrete.Uint() > max {
violations += FailValMax
}
}
}
case reflect.Float32, reflect.Float64:
if minMax[0] != "" {
min, err := strconv.ParseFloat(minMax[0], 64)
if err == nil {
if concrete.Float() < min {
violations += FailValMin
}
}
}
if len(minMax) > 1 && minMax[1] != "" {
max, err := strconv.ParseFloat(minMax[1], 64)
if err == nil {
if concrete.Float() > max {
violations += FailValMax
}
}
}
default:
// Not a numeric type → record a mismatch.
violations = +FailType
}
default:
}
}
}
}
// regexp checked only if the field value is not a nil pointer
if !isNilPointer {
regexpTagName := tagName + "_regexp"
if pattern := structField.Tag.Get(regexpTagName); pattern != "" {
if kind == reflect.String {
compiled, err := getCompiledRegexp(pattern)
if err != nil || !compiled.MatchString(concrete.String()) {
// configuration error is considered a failed regexp
violations += FailRegExp
}
}
}
}
ok := violations == 0
return ok, violations
}