forked from go-ozzo/ozzo-validation
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathstruct.go
More file actions
237 lines (215 loc) · 7.15 KB
/
struct.go
File metadata and controls
237 lines (215 loc) · 7.15 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
// Copyright 2016 Qiang Xue. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package validation
import (
"context"
"errors"
"fmt"
"reflect"
"strings"
)
var (
// ErrStructPointer is the error that a struct being validated is not specified as a pointer.
ErrStructPointer = errors.New("only a pointer to a struct can be validated")
// GetErrorFieldName is used to get the desired field name for a struct field, overriding the default getErrorFieldName
GetErrorFieldName func(f *reflect.StructField) string = getErrorFieldName
)
type (
// ErrFieldPointer is the error that a field is not specified as a pointer.
ErrFieldPointer int
// ErrFieldNotFound is the error that a field cannot be found in the struct.
ErrFieldNotFound int
// FieldRules represents a rule set associated with a struct field.
FieldRules struct {
fieldPtr interface{}
rules []Rule
validatePtrValue bool
}
)
// Error returns the error string of ErrFieldPointer.
func (e ErrFieldPointer) Error() string {
return fmt.Sprintf("field #%v must be specified as a pointer", int(e))
}
// Error returns the error string of ErrFieldNotFound.
func (e ErrFieldNotFound) Error() string {
return fmt.Sprintf("field #%v cannot be found in the struct", int(e))
}
// ValidateStruct validates a struct by checking the specified struct fields against the corresponding validation rules.
// Note that the struct being validated must be specified as a pointer to it. If the pointer is nil, it is considered valid.
// Use Field() to specify struct fields that need to be validated. Each Field() call specifies a single field which
// should be specified as a pointer to the field. A field can be associated with multiple rules.
// For example,
//
// value := struct {
// Name string
// Value string
// }{"name", "demo"}
// err := validation.ValidateStruct(&value,
// validation.Field(&a.Name, validation.Required),
// validation.Field(&a.Value, validation.Required, validation.Length(5, 10)),
// )
// fmt.Println(err)
// // Value: the length must be between 5 and 10.
//
// An error will be returned if validation fails.
func ValidateStruct(structPtr interface{}, fields ...*FieldRules) error {
return ValidateStructWithContext(nil, structPtr, fields...)
}
// ValidateStructWithContext validates a struct with the given context.
// The only difference between ValidateStructWithContext and ValidateStruct is that the former will
// validate struct fields with the provided context.
// Please refer to ValidateStruct for the detailed instructions on how to use this function.
func ValidateStructWithContext(ctx context.Context, structPtr interface{}, fields ...*FieldRules) error {
value := reflect.ValueOf(structPtr)
if value.Kind() != reflect.Ptr || !value.IsNil() && value.Elem().Kind() != reflect.Struct {
// must be a pointer to a struct
return NewInternalError(ErrStructPointer)
}
if value.IsNil() {
// treat a nil struct pointer as valid
return nil
}
value = value.Elem()
errs := Errors{}
for i, fr := range fields {
fv := reflect.ValueOf(fr.fieldPtr)
if fv.Kind() != reflect.Ptr {
return NewInternalError(ErrFieldPointer(i))
}
ft := findStructField(value, fv)
if ft == nil {
return NewInternalError(ErrFieldNotFound(i))
}
var validateValue interface{}
if !fr.validatePtrValue {
validateValue = fv.Elem().Interface()
} else {
validateValue = fv.Interface()
}
var err error
if ctx == nil {
err = Validate(validateValue, fr.rules...)
} else {
err = ValidateWithContext(ctx, validateValue, fr.rules...)
}
if err != nil {
if ie, ok := err.(InternalError); ok && ie.InternalError() != nil {
return err
}
if ft.Anonymous {
// merge errors from anonymous struct field
if es, ok := err.(Errors); ok {
for name, value := range es {
errs[name] = value
}
continue
}
}
errs[GetErrorFieldName(ft)] = err
}
}
if len(errs) > 0 {
return errs
}
return nil
}
// Field specifies a struct field and the corresponding validation rules.
// The struct field must be specified as a pointer to it.
func Field(fieldPtr interface{}, rules ...Rule) *FieldRules {
return &FieldRules{
fieldPtr: fieldPtr,
rules: rules,
}
}
// FieldStruct specifies a struct field and the corresponding validation field rules.
// The struct field must be specified as a pointer to struct.
// example,
//
// value := struct {
// NestedStruct struct {
// Name string
// }
// }{NestedStruct: struct{Name string}{}}
// err := validation.ValidateStruct(
// &value,
// validation.FieldStruct(
// &value.NestedStruct,
// validation.Field(&value.NestedStruct.Name, validation.Required),
// ),
// )
func FieldStruct(structPtr interface{}, fields ...*FieldRules) *FieldRules {
return &FieldRules{
fieldPtr: structPtr,
rules: []Rule{&inlineRule{
f: func(value interface{}) error {
return ValidateStruct(value, fields...)
},
fc: func(ctx context.Context, value interface{}) error {
return ValidateStructWithContext(ctx, value, fields...)
},
}},
validatePtrValue: true,
}
}
// ErrorFieldName gets the value of the ErrorTag for the given field in the given struct
func ErrorFieldName(structPtr interface{}, fieldPtr interface{}) (string, error) {
value := reflect.ValueOf(structPtr)
if value.Kind() != reflect.Ptr || !value.IsNil() && value.Elem().Kind() != reflect.Struct {
// must be a pointer to a struct
return "", NewInternalError(ErrStructPointer)
}
if value.IsNil() {
// treat a nil struct pointer as valid
return "", nil
}
value = value.Elem()
fv := reflect.ValueOf(fieldPtr)
if fv.Kind() != reflect.Ptr {
// must be a pointer to a field
return "", NewInternalError(ErrFieldPointer(0))
}
ft := findStructField(value, fv)
if ft == nil {
return "", NewInternalError(ErrFieldNotFound(0))
}
return getErrorFieldName(ft), nil
}
// findStructField looks for a field in the given struct.
// The field being looked for should be a pointer to the actual struct field.
// If found, the field info will be returned. Otherwise, nil will be returned.
func findStructField(structValue reflect.Value, fieldValue reflect.Value) *reflect.StructField {
ptr := fieldValue.Pointer()
for i := structValue.NumField() - 1; i >= 0; i-- {
sf := structValue.Type().Field(i)
if ptr == structValue.Field(i).UnsafeAddr() {
// do additional type comparison because it's possible that the address of
// an embedded struct is the same as the first field of the embedded struct
if sf.Type == fieldValue.Elem().Type() {
return &sf
}
}
if sf.Anonymous {
// delve into anonymous struct to look for the field
fi := structValue.Field(i)
if sf.Type.Kind() == reflect.Ptr {
fi = fi.Elem()
}
if fi.Kind() == reflect.Struct {
if f := findStructField(fi, fieldValue); f != nil {
return f
}
}
}
}
return nil
}
// getErrorFieldName returns the name that should be used to represent the validation error of a struct field.
func getErrorFieldName(f *reflect.StructField) string {
if tag := f.Tag.Get(ErrorTag); tag != "" && tag != "-" {
if cps := strings.SplitN(tag, ",", 2); cps[0] != "" {
return cps[0]
}
}
return f.Name
}