forked from gin-gonic/gin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
validation.go
45 lines (38 loc) · 1013 Bytes
/
validation.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
package gin
import (
"errors"
"reflect"
"strings"
)
func Validate(c *Context, obj interface{}) error {
var err error
typ := reflect.TypeOf(obj)
val := reflect.ValueOf(obj)
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
val = val.Elem()
}
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
fieldValue := val.Field(i).Interface()
zero := reflect.Zero(field.Type).Interface()
// Validate nested and embedded structs (if pointer, only do so if not nil)
if field.Type.Kind() == reflect.Struct ||
(field.Type.Kind() == reflect.Ptr && !reflect.DeepEqual(zero, fieldValue)) {
err = Validate(c, fieldValue)
}
if strings.Index(field.Tag.Get("binding"), "required") > -1 {
if reflect.DeepEqual(zero, fieldValue) {
name := field.Name
if j := field.Tag.Get("json"); j != "" {
name = j
} else if f := field.Tag.Get("form"); f != "" {
name = f
}
err = errors.New("Required " + name)
c.Error(err, "json validation")
}
}
}
return err
}