forked from gookit/validate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidate.go
415 lines (357 loc) · 9.87 KB
/
validate.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
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
// Package validate is a generic go data validate, filtering library.
//
// Source code and other details for the project are available at GitHub:
//
// https://github.com/gookit/validate
package validate
import (
"encoding/json"
"io"
"net/http"
"net/url"
"reflect"
"regexp"
"strings"
"github.com/gookit/goutil/reflects"
)
// M is short name for map[string]any
type M map[string]any
// MS is short name for map[string]string
type MS map[string]string
// SValues simple values
type SValues map[string][]string
// One get one item's value string
func (ms MS) One() string {
for _, msg := range ms {
return msg
}
return ""
}
// String convert map[string]string to string
func (ms MS) String() string {
if len(ms) == 0 {
return ""
}
ss := make([]string, 0, len(ms))
for name, msg := range ms {
ss = append(ss, " "+name+": "+msg)
}
return strings.Join(ss, "\n")
}
// GlobalOption settings for validate
type GlobalOption struct {
// FilterTag name in the struct tags.
//
// default: filter
FilterTag string
// ValidateTag in the struct tags.
//
// default: validate
ValidateTag string
// FieldTag the output field name in the struct tags.
// it as placeholder on error message.
//
// default: json
FieldTag string
// LabelTag the display name in the struct tags.
// use for define field translate name on error.
//
// default: label
LabelTag string
// MessageTag define error message for the field.
//
// default: message
MessageTag string
// DefaultTag define default value for the field.
//
// tag: default TODO
DefaultTag string
// StopOnError If true: An error occurs, it will cease to continue to verify
StopOnError bool
// SkipOnEmpty Skip check on field not exist or value is empty
SkipOnEmpty bool
// UpdateSource Whether to update source field value, useful for struct validate
UpdateSource bool
// CheckDefault Whether to validate the default value set by the user
CheckDefault bool
// CheckZero Whether validate the default zero value. (intX,uintX: 0, string: "")
CheckZero bool
// ErrKeyFmt config. TODO
//
// allow:
// - 0 use struct field name as key. (for compatible)
// - 1 use FieldTag defined name as key.
ErrKeyFmt int8
// CheckSubOnParentMarked True: only collect sub-struct rule on current field has rule.
CheckSubOnParentMarked bool
// ValidatePrivateFields Whether to validate private fields or not, especially when inheriting other other structs.
//
// type foo struct {
// Field int `json:"field" validate:"required"`
// }
// type bar struct {
// foo // <-- validate this field
// Field2 int `json:"field2" validate:"required"`
// }
//
// default: false
ValidatePrivateFields bool
}
// global options
var gOpt = newGlobalOption()
// Config global options
func Config(fn func(opt *GlobalOption)) {
fn(gOpt)
}
// ResetOption reset global option
func ResetOption() {
*gOpt = *newGlobalOption()
}
// Option get global options
func Option() GlobalOption {
return *gOpt
}
func newGlobalOption() *GlobalOption {
return &GlobalOption{
StopOnError: true,
SkipOnEmpty: true,
// tag name in struct tags
FieldTag: fieldTag,
// label tag - display name in struct tags
LabelTag: labelTag,
// tag name in struct tags
FilterTag: filterTag,
MessageTag: messageTag,
// tag name in struct tags
ValidateTag: validateTag,
}
}
func newValidation(data DataFace) *Validation {
v := &Validation{
Errors: make(Errors),
// add data source on usage
data: data,
// create message translator
// trans: StdTranslator,
trans: NewTranslator(),
// validated data
safeData: make(map[string]any),
// validator names
validators: make(map[string]int8),
// filtered data
filteredData: make(map[string]any),
// default config
StopOnError: gOpt.StopOnError,
SkipOnEmpty: gOpt.SkipOnEmpty,
}
// init build in context validator
v.validatorValues = map[string]reflect.Value{
"required": reflect.ValueOf(v.Required),
"requiredIf": reflect.ValueOf(v.RequiredIf),
"requiredUnless": reflect.ValueOf(v.RequiredUnless),
"requiredWith": reflect.ValueOf(v.RequiredWith),
"requiredWithAll": reflect.ValueOf(v.RequiredWithAll),
"requiredWithout": reflect.ValueOf(v.RequiredWithout),
"requiredWithoutAll": reflect.ValueOf(v.RequiredWithoutAll),
// field compare
"eqField": reflect.ValueOf(v.EqField),
"neField": reflect.ValueOf(v.NeField),
"gtField": reflect.ValueOf(v.GtField),
"gteField": reflect.ValueOf(v.GteField),
"ltField": reflect.ValueOf(v.LtField),
"lteField": reflect.ValueOf(v.LteField),
// file upload check
"isFile": reflect.ValueOf(v.IsFormFile),
"isImage": reflect.ValueOf(v.IsFormImage),
"inMimeTypes": reflect.ValueOf(v.InMimeTypes),
}
v.validatorMetas = make(map[string]*funcMeta)
// collect meta info
for n, fv := range v.validatorValues {
v.validators[n] = 1 // built in
v.validatorMetas[n] = newFuncMeta(n, true, fv)
}
// v.pool = &sync.Pool{
// New: func() any {
// return &Validation{
// v: v,
// }
// },
// }
return v
}
/*************************************************************
* quick create Validation
*************************************************************/
// New create a Validation instance
// data support:
// - DataFace
// - M/map[string]any
// - SValues/url.Values/map[string][]string
// - struct ptr
func New(data any, scene ...string) *Validation {
switch td := data.(type) {
case DataFace:
return NewValidation(td, scene...)
case M:
return FromMap(td).Create().SetScene(scene...)
case map[string]any:
return FromMap(td).Create().SetScene(scene...)
case SValues:
return FromURLValues(url.Values(td)).Create().SetScene(scene...)
case url.Values:
return FromURLValues(td).Create().SetScene(scene...)
case map[string][]string:
return FromURLValues(td).Create().SetScene(scene...)
}
return Struct(data, scene...)
}
// NewWithOptions new Validation with options
// func NewWithOptions(data any, fn func(opt *GlobalOption)) *Validation {
// fn(gOpt)
// return New(data)
// }
// Map validation create
func Map(m map[string]any, scene ...string) *Validation {
return FromMap(m).Create().SetScene(scene...)
}
// MapWithRules validation create and with rules
// func MapWithRules(m map[string]any, rules MS) *Validation {
// return FromMap(m).Create().StringRules(rules)
// }
// JSON create validation from JSON string.
func JSON(s string, scene ...string) *Validation {
return mustNewValidation(FromJSON(s)).SetScene(scene...)
}
// Struct validation create
func Struct(s any, scene ...string) *Validation {
return mustNewValidation(FromStruct(s)).SetScene(scene...)
}
// Request validation create
func Request(r *http.Request) *Validation {
return mustNewValidation(FromRequest(r))
}
func mustNewValidation(d DataFace, err error) *Validation {
if d == nil {
if err != nil {
return NewValidation(d).WithError(err)
}
return NewValidation(d)
}
return d.Create(err)
}
/*************************************************************
* create data-source instance
*************************************************************/
// FromMap build data instance.
func FromMap(m map[string]any) *MapData {
data := &MapData{}
if m != nil {
data.Map = m
data.value = reflect.ValueOf(m)
}
return data
}
// FromJSON string build data instance.
func FromJSON(s string) (*MapData, error) {
return FromJSONBytes([]byte(s))
}
// FromJSONBytes string build data instance.
func FromJSONBytes(bs []byte) (*MapData, error) {
mp := map[string]any{}
if err := json.Unmarshal(bs, &mp); err != nil {
return nil, err
}
data := &MapData{
Map: mp,
value: reflect.ValueOf(mp),
// save JSON bytes
bodyJSON: bs,
}
return data, nil
}
// FromStruct create a Data from struct
func FromStruct(s any) (*StructData, error) {
data := &StructData{
ValidateTag: gOpt.ValidateTag,
// init map
fieldNames: make(map[string]int8),
fieldValues: make(map[string]reflect.Value),
}
if s == nil {
return data, ErrInvalidData
}
val := reflects.Elem(reflect.ValueOf(s))
typ := val.Type()
if val.Kind() != reflect.Struct || typ == timeType {
return data, ErrInvalidData
}
data.src = s
data.value = val
data.valueTpy = typ
return data, nil
}
var jsonContent = regexp.MustCompile(`(?i)application/((\w|\.|-)+\+)?json(-seq)?`)
// FromRequest collect data from request instance
func FromRequest(r *http.Request, maxMemoryLimit ...int64) (DataFace, error) {
// no body. like GET DELETE ....
if r.Method != "POST" && r.Method != "PUT" && r.Method != "PATCH" {
return FromURLValues(r.URL.Query()), nil
}
cType := r.Header.Get("Content-Type")
// contains file uploaded form
// strings.HasPrefix(mediaType, "multipart/")
if strings.Contains(cType, "multipart/form-data") {
maxMemory := defaultMaxMemory
if len(maxMemoryLimit) > 0 {
maxMemory = maxMemoryLimit[0]
}
if err := r.ParseMultipartForm(maxMemory); err != nil {
return nil, err
}
// collect from values
data := FromURLValues(r.MultipartForm.Value)
// collect uploaded files
data.AddFiles(r.MultipartForm.File)
// add queries data
data.AddValues(r.URL.Query())
return data, nil
}
// basic POST form. content type: application/x-www-form-urlencoded
if strings.Contains(cType, "form-urlencoded") {
if err := r.ParseForm(); err != nil {
return nil, err
}
data := FromURLValues(r.PostForm)
// add queries data
data.AddValues(r.URL.Query())
return data, nil
}
// JSON body request
if jsonContent.MatchString(cType) {
bs, err := io.ReadAll(r.Body)
if err != nil {
return nil, err
}
return FromJSONBytes(bs)
}
return nil, ErrEmptyData
}
// FromURLValues build data instance.
func FromURLValues(values url.Values) *FormData {
data := newFormData()
for key, vals := range values {
for _, val := range vals {
data.Add(key, val)
}
}
return data
}
// FromQuery build data instance.
//
// Usage:
//
// validate.FromQuery(r.URL.Query()).Create()
func FromQuery(values url.Values) *FormData {
return FromURLValues(values)
}