-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidator.go
More file actions
310 lines (271 loc) · 9.98 KB
/
validator.go
File metadata and controls
310 lines (271 loc) · 9.98 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
package validator
import (
"fmt"
"slices"
"strings"
"github.com/siherrmann/validator/helper"
"github.com/siherrmann/validator/model"
"github.com/siherrmann/validator/parser"
"github.com/siherrmann/validator/validators"
)
type ValidationFunc func(input any, astValue *model.AstValue) error
// Validator is the main struct for validation.
type Validator struct {
ValidationFuncs map[string]ValidationFunc
}
// NewValidator creates a new Validator instance with an empty validation functions map.
func NewValidator() *Validator {
return &Validator{
ValidationFuncs: make(map[string]ValidationFunc),
}
}
// AddValidationFunc adds a custom validation function to the Validator.
// The function can be used in validation requirements with the name provided (`fun<name>`).
func (r *Validator) AddValidationFunc(fn ValidationFunc, name string) {
r.ValidationFuncs[name] = fn
}
// Validate validates a given struct by the given tagType.
// It checks if the keys are in the struct and validates the values.
// It returns an error if the validation fails.
func (r *Validator) Validate(v any, tagType ...string) error {
tagTypeSet := model.VLD
if len(tagType) > 0 {
tagTypeSet = tagType[0]
}
jsonMap := map[string]any{}
err := helper.UnmapStructToJsonMap(v, &jsonMap)
if err != nil {
return fmt.Errorf("error unmapping struct to json map: %v", err)
}
validations, err := GetValidationsFromStruct(v, tagTypeSet)
if err != nil {
return fmt.Errorf("error getting validations from struct: %v", err)
}
_, err = r.ValidateWithValidation(jsonMap, validations)
if err != nil {
return fmt.Errorf("error validating struct: %v", err)
}
return nil
}
// ValidateAndUpdate validates a given JsonMap by the given validations and updates the struct.
// It checks if the keys are in the map, validates the values and updates the struct if the validation passes.
// It returns an error if the validation fails or if the struct cannot be updated.
func (r *Validator) ValidateAndUpdate(jsonInput map[string]any, structToUpdate any, tagType ...string) error {
tagTypeSet := model.VLD
if len(tagType) > 0 {
tagTypeSet = tagType[0]
}
validations, err := GetValidationsFromStruct(structToUpdate, tagTypeSet)
if err != nil {
return fmt.Errorf("error getting validations from struct: %v", err)
}
validatedMap, err := r.ValidateWithValidation(jsonInput, validations)
if err != nil {
return fmt.Errorf("error validating struct: %v", err)
}
err = helper.MapJsonMapToStruct(validatedMap, structToUpdate)
if err != nil {
return fmt.Errorf("error mapping json map to struct: %v", err)
}
return nil
}
// ValidateAndUpdateWithValidation validates a given JsonMap by the given validations and updates the map.
// It checks if the keys are in the map, validates the values and updates the map if the validation passes.
// It returns an error if the validation fails or if the map cannot be updated.
func (r *Validator) ValidateAndUpdateWithValidation(jsonInput map[string]any, mapToUpdate *map[string]any, validations []model.Validation) error {
validatedValues, err := r.ValidateWithValidation(jsonInput, validations)
if err != nil {
return fmt.Errorf("error validating json map: %v", err)
}
for k, v := range validatedValues {
(*mapToUpdate)[k] = v
}
return nil
}
// ValidateWithValidation validates a given JsonMap by the given validations.
// This is the main validation function that is used for all validation.
// It checks if the keys are in the map, validates the values and returns a new JsonMap.
//
// If a validation has groups, it checks if the values are valid for the groups.
// If a validation has a key that is already in the map, it returns an error.
//
// It returns a new JsonMap with the validated values or an error if the validation fails.
func (r *Validator) ValidateWithValidation(jsonInput map[string]any, validations []model.Validation) (map[string]any, error) {
keys := []string{}
groups := map[string]*model.Group{}
groupSize := map[string]int{}
groupErrors := map[string][]error{}
validateValues := map[string]any{}
for validationIndex := range validations {
validation := validations[validationIndex]
if len(validation.Key) > 0 && slices.Contains(keys, validation.Key) {
return map[string]any{}, fmt.Errorf("duplicate validation key: %v", validation.Key)
} else {
keys = append(keys, validation.Key)
}
for _, g := range validation.Groups {
groups[g.Name] = g
groupSize[g.Name]++
}
var ok bool
var jsonValue any
if jsonValue, ok = jsonInput[validation.Key]; !ok {
if validation.Default != "" {
jsonValue = validation.Default
ok = true
} else if strings.TrimSpace(validation.Requirement) == string(model.NONE) {
continue
} else if len(validation.Groups) == 0 {
return map[string]any{}, fmt.Errorf("json %v key not in map", validation.Key)
} else {
for _, group := range validation.Groups {
groupErrors[group.Name] = append(groupErrors[group.Name], fmt.Errorf("json %v key not in map", validation.Key))
}
continue
}
}
if validation.OmitEmpty && jsonValue == "" {
continue
}
var err error
switch validation.Type {
case model.Struct:
if jsonValueMap, ok := jsonValue.(map[string]any); ok {
jsonValue, err = r.ValidateWithValidation(jsonValueMap, validation.InnerValidation)
if err != nil {
return map[string]any{}, fmt.Errorf("field %v invalid: %v", validation.Key, err.Error())
}
} else {
err = r.ValidateValueWithParser(jsonValue, &validation)
}
case model.Array:
if helper.IsArray(jsonValue) && len(validation.InnerValidation) > 0 {
jsonArray, ok := jsonValue.([]any)
if !ok {
return map[string]any{}, fmt.Errorf("field %v must be of type array, was %T", validation.Key, jsonValue)
}
validatedArray := []any{}
for _, jsonValueInner := range jsonArray {
jsonValueInnerMap, err := helper.GetValidMap(jsonValueInner)
if err != nil {
return map[string]any{}, fmt.Errorf("field %v invalid: %v", validation.Key, err.Error())
}
validatedInnerMap, err := r.ValidateWithValidation(jsonValueInnerMap, validation.InnerValidation)
if err != nil {
return map[string]any{}, fmt.Errorf("field %v invalid: %v", validation.Key, err.Error())
}
validatedArray = append(validatedArray, validatedInnerMap)
}
jsonValue = validatedArray
} else if helper.IsArray(jsonValue) {
err = r.ValidateValueWithParser(jsonValue, &validation)
} else if helper.IsString(jsonValue) {
// Check if the value is a string from a url value.
jsonValue = []string{jsonValue.(string)}
err = r.ValidateValueWithParser(jsonValue, &validation)
}
default:
err = r.ValidateValueWithParser(jsonValue, &validation)
}
if err != nil {
if validation.Default != "" {
jsonValue = validation.Default
err = nil
} else if len(validation.Groups) == 0 {
return map[string]any{}, fmt.Errorf("field %v invalid: %v", validation.Key, err.Error())
} else {
for _, group := range validation.Groups {
groupErrors[group.Name] = append(groupErrors[group.Name], fmt.Errorf("field %v invalid: %v", validation.Key, err.Error()))
}
continue
}
}
validateValues[validation.Key] = jsonValue
}
err := validators.ValidateGroups(groups, groupSize, groupErrors)
if err != nil {
return map[string]any{}, err
}
return validateValues, nil
}
// ValidateValueWithParser validates a value against a given validation using the parser.
// It parses the validation requirement and runs the validation function on the input value.
//
// It returns an error if the validation fails.
func (r *Validator) ValidateValueWithParser(input any, validation *model.Validation) error {
var astValue *model.AstValue
if validation.RequirementAST != nil {
astValue = validation.RequirementAST
} else {
p := parser.NewParser()
v, err := p.ParseValidation(validation.Requirement)
if err != nil {
return err
}
astValue = v.RootValue
}
err := r.RunValidatorsOnConditionGroup(input, astValue)
if err != nil {
return err
}
return nil
}
// RunFuncOnConditionGroup runs the function [f] on each condition in the [astValue].
// If the condition is a group, it recursively calls itself on the group.
// If the condition is a condition, it calls the function [f] with the input and the condition.
// If the operator is AND, it returns an error if any condition fails.
// If the operator is OR, it collects all errors and returns them if all conditions fail.
func (r *Validator) RunValidatorsOnConditionGroup(input any, astValue *model.AstValue) error {
var errors []error
for i, v := range astValue.ConditionGroup {
var err error
switch v.Type {
case model.EMPTY:
return nil
case model.GROUP:
err = r.RunValidatorsOnConditionGroup(input, v)
case model.CONDITION:
switch v.ConditionType {
case model.NONE, model.DEF:
continue
case model.EQUAL:
err = validators.ValidateEqual(input, v)
case model.NOT_EQUAL:
err = validators.ValidateNotEqual(input, v)
case model.MIN_VALUE:
err = validators.ValidateMin(input, v)
case model.MAX_VALUE:
err = validators.ValidateMax(input, v)
case model.CONTAINS:
err = validators.ValidateContains(input, v)
case model.NOT_CONTAINS:
err = validators.ValidateNotContains(input, v)
case model.FROM:
err = validators.ValidateFrom(input, v)
case model.NOT_FROM:
err = validators.ValidateNotFrom(input, v)
case model.REGX:
err = validators.ValidateRegex(input, v)
case model.FUNC:
fun, ok := r.ValidationFuncs[v.ConditionValue]
if !ok {
return fmt.Errorf("unknown validation function: %v", v.ConditionValue)
}
err = fun(input, v)
default:
return fmt.Errorf("unknown condition type: %v", v.ConditionType)
}
}
if err != nil {
if (i == 0 && v.Operator == model.OR) || (i > 0 && astValue.ConditionGroup[i-1].Operator == model.OR) {
errors = append(errors, err)
} else {
return err
}
}
}
if len(astValue.ConditionGroup) > 0 && len(errors) >= len(astValue.ConditionGroup) {
return fmt.Errorf("no condition fulfilled, all errors: %v", errors)
}
return nil
}