-
Notifications
You must be signed in to change notification settings - Fork 24
/
validate_required.go
57 lines (45 loc) · 1.27 KB
/
validate_required.go
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
package valiant
import (
"reflect"
"strconv"
)
func validateRequired(typed interface{}, untyped interface{}) error {
parentValue, parentType := reflectedParent(typed)
// TODO: Add JSON array type support here
parentUntyped := untyped.(map[string]interface{})
for i := 0; i < parentType.NumField(); i++ {
childField := parentType.Field(i)
childValue := parentValue.FieldByName(childField.Name)
tag := childField.Tag.Get("json")
err := validateRequiredField(childField, parentUntyped)
if err != nil {
return err
}
if childValue.Kind() == reflect.Struct {
err = validateRequired(childValue.Interface(), parentUntyped[tag])
if err != nil {
return err
}
}
}
return nil
}
func validateRequiredField(field reflect.StructField, parentUntyped map[string]interface{}) error {
if required(field) {
fieldName := jsonName(field)
if _, ok := parentUntyped[fieldName]; !ok {
return RequiredFieldError{ErrorMessage: "Missing required field '" + fieldName + "'"}
}
}
return nil
}
func required(field reflect.StructField) bool {
if tag := field.Tag.Get("validate-required"); tag != "" {
required, err := strconv.ParseBool(tag)
if err != nil {
panic("we got an error on parsing the validate-required tag")
}
return required
}
return false
}