-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate_fields.go
More file actions
60 lines (52 loc) · 1.55 KB
/
validate_fields.go
File metadata and controls
60 lines (52 loc) · 1.55 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
package sentinal
import (
"reflect"
"github.com/ZeroTechh/hades"
"github.com/pkg/errors"
)
// ValidateFields is used to only validate non nill fields in an object
func ValidateFields(
object interface{},
schema map[string]map[string]string,
customFunctionsArg ...map[string]func(reflect.Value, string) (bool, string, error)) (
bool,
map[string][]string,
error) {
valueOf := reflect.ValueOf(object)
typeOf := reflect.TypeOf(object)
output := map[string][]string{}
// If custom functions are given, add it to functions map
if customFunctionsArg != nil {
for name, function := range customFunctionsArg[0] {
functions[name] = function
}
}
for i := 0; i < typeOf.NumField(); i++ {
curField := typeOf.Field(i)
if !valueOf.Field(i).IsZero() {
if args, ok := schema[curField.Name]; ok {
valid, msgs, err := validateField(valueOf.Field(i), args)
if err != nil {
err = errors.Wrap(err, "Error while validating field")
return false, map[string][]string{}, err
} else if !valid {
output[curField.Name] = msgs
}
}
}
}
return len(output) <= 0, output, nil
}
// ValidateFieldsWithYAML is used to validate non nill fields in an object with yaml schema
func ValidateFieldsWithYAML(
object interface{},
schemaFile string,
schemaPaths []string,
customFunctionsArg ...map[string]func(reflect.Value, string) (bool, string, error)) (
bool,
map[string][]string,
error) {
config := hades.GetConfig(schemaFile, schemaPaths)
schema := processYAMLData(config.Data)
return ValidateFields(object, schema, customFunctionsArg...)
}