podman

Форк
0
1474 строки · 38.2 Кб
1
/*
2
Package validator implements value validations for structs and individual fields
3
based on tags.
4

5
It can also handle Cross-Field and Cross-Struct validation for nested structs
6
and has the ability to dive into arrays and maps of any type.
7

8
see more examples https://github.com/go-playground/validator/tree/master/_examples
9

10
# Singleton
11

12
Validator is designed to be thread-safe and used as a singleton instance.
13
It caches information about your struct and validations,
14
in essence only parsing your validation tags once per struct type.
15
Using multiple instances neglects the benefit of caching.
16
The not thread-safe functions are explicitly marked as such in the documentation.
17

18
# Validation Functions Return Type error
19

20
Doing things this way is actually the way the standard library does, see the
21
file.Open method here:
22

23
	https://golang.org/pkg/os/#Open.
24

25
The authors return type "error" to avoid the issue discussed in the following,
26
where err is always != nil:
27

28
	http://stackoverflow.com/a/29138676/3158232
29
	https://github.com/go-playground/validator/issues/134
30

31
Validator only InvalidValidationError for bad validation input, nil or
32
ValidationErrors as type error; so, in your code all you need to do is check
33
if the error returned is not nil, and if it's not check if error is
34
InvalidValidationError ( if necessary, most of the time it isn't ) type cast
35
it to type ValidationErrors like so err.(validator.ValidationErrors).
36

37
# Custom Validation Functions
38

39
Custom Validation functions can be added. Example:
40

41
	// Structure
42
	func customFunc(fl validator.FieldLevel) bool {
43

44
		if fl.Field().String() == "invalid" {
45
			return false
46
		}
47

48
		return true
49
	}
50

51
	validate.RegisterValidation("custom tag name", customFunc)
52
	// NOTES: using the same tag name as an existing function
53
	//        will overwrite the existing one
54

55
# Cross-Field Validation
56

57
Cross-Field Validation can be done via the following tags:
58
  - eqfield
59
  - nefield
60
  - gtfield
61
  - gtefield
62
  - ltfield
63
  - ltefield
64
  - eqcsfield
65
  - necsfield
66
  - gtcsfield
67
  - gtecsfield
68
  - ltcsfield
69
  - ltecsfield
70

71
If, however, some custom cross-field validation is required, it can be done
72
using a custom validation.
73

74
Why not just have cross-fields validation tags (i.e. only eqcsfield and not
75
eqfield)?
76

77
The reason is efficiency. If you want to check a field within the same struct
78
"eqfield" only has to find the field on the same struct (1 level). But, if we
79
used "eqcsfield" it could be multiple levels down. Example:
80

81
	type Inner struct {
82
		StartDate time.Time
83
	}
84

85
	type Outer struct {
86
		InnerStructField *Inner
87
		CreatedAt time.Time      `validate:"ltecsfield=InnerStructField.StartDate"`
88
	}
89

90
	now := time.Now()
91

92
	inner := &Inner{
93
		StartDate: now,
94
	}
95

96
	outer := &Outer{
97
		InnerStructField: inner,
98
		CreatedAt: now,
99
	}
100

101
	errs := validate.Struct(outer)
102

103
	// NOTE: when calling validate.Struct(val) topStruct will be the top level struct passed
104
	//       into the function
105
	//       when calling validate.VarWithValue(val, field, tag) val will be
106
	//       whatever you pass, struct, field...
107
	//       when calling validate.Field(field, tag) val will be nil
108

109
# Multiple Validators
110

111
Multiple validators on a field will process in the order defined. Example:
112

113
	type Test struct {
114
		Field `validate:"max=10,min=1"`
115
	}
116

117
	// max will be checked then min
118

119
Bad Validator definitions are not handled by the library. Example:
120

121
	type Test struct {
122
		Field `validate:"min=10,max=0"`
123
	}
124

125
	// this definition of min max will never succeed
126

127
# Using Validator Tags
128

129
Baked In Cross-Field validation only compares fields on the same struct.
130
If Cross-Field + Cross-Struct validation is needed you should implement your
131
own custom validator.
132

133
Comma (",") is the default separator of validation tags. If you wish to
134
have a comma included within the parameter (i.e. excludesall=,) you will need to
135
use the UTF-8 hex representation 0x2C, which is replaced in the code as a comma,
136
so the above will become excludesall=0x2C.
137

138
	type Test struct {
139
		Field `validate:"excludesall=,"`    // BAD! Do not include a comma.
140
		Field `validate:"excludesall=0x2C"` // GOOD! Use the UTF-8 hex representation.
141
	}
142

143
Pipe ("|") is the 'or' validation tags deparator. If you wish to
144
have a pipe included within the parameter i.e. excludesall=| you will need to
145
use the UTF-8 hex representation 0x7C, which is replaced in the code as a pipe,
146
so the above will become excludesall=0x7C
147

148
	type Test struct {
149
		Field `validate:"excludesall=|"`    // BAD! Do not include a pipe!
150
		Field `validate:"excludesall=0x7C"` // GOOD! Use the UTF-8 hex representation.
151
	}
152

153
# Baked In Validators and Tags
154

155
Here is a list of the current built in validators:
156

157
# Skip Field
158

159
Tells the validation to skip this struct field; this is particularly
160
handy in ignoring embedded structs from being validated. (Usage: -)
161

162
	Usage: -
163

164
# Or Operator
165

166
This is the 'or' operator allowing multiple validators to be used and
167
accepted. (Usage: rgb|rgba) <-- this would allow either rgb or rgba
168
colors to be accepted. This can also be combined with 'and' for example
169
( Usage: omitempty,rgb|rgba)
170

171
	Usage: |
172

173
# StructOnly
174

175
When a field that is a nested struct is encountered, and contains this flag
176
any validation on the nested struct will be run, but none of the nested
177
struct fields will be validated. This is useful if inside of your program
178
you know the struct will be valid, but need to verify it has been assigned.
179
NOTE: only "required" and "omitempty" can be used on a struct itself.
180

181
	Usage: structonly
182

183
# NoStructLevel
184

185
Same as structonly tag except that any struct level validations will not run.
186

187
	Usage: nostructlevel
188

189
# Omit Empty
190

191
Allows conditional validation, for example if a field is not set with
192
a value (Determined by the "required" validator) then other validation
193
such as min or max won't run, but if a value is set validation will run.
194

195
	Usage: omitempty
196

197
# Omit Nil
198

199
Allows to skip the validation if the value is nil (same as omitempty, but
200
only for the nil-values).
201

202
	Usage: omitnil
203

204
# Dive
205

206
This tells the validator to dive into a slice, array or map and validate that
207
level of the slice, array or map with the validation tags that follow.
208
Multidimensional nesting is also supported, each level you wish to dive will
209
require another dive tag. dive has some sub-tags, 'keys' & 'endkeys', please see
210
the Keys & EndKeys section just below.
211

212
	Usage: dive
213

214
Example #1
215

216
	[][]string with validation tag "gt=0,dive,len=1,dive,required"
217
	// gt=0 will be applied to []
218
	// len=1 will be applied to []string
219
	// required will be applied to string
220

221
Example #2
222

223
	[][]string with validation tag "gt=0,dive,dive,required"
224
	// gt=0 will be applied to []
225
	// []string will be spared validation
226
	// required will be applied to string
227

228
Keys & EndKeys
229

230
These are to be used together directly after the dive tag and tells the validator
231
that anything between 'keys' and 'endkeys' applies to the keys of a map and not the
232
values; think of it like the 'dive' tag, but for map keys instead of values.
233
Multidimensional nesting is also supported, each level you wish to validate will
234
require another 'keys' and 'endkeys' tag. These tags are only valid for maps.
235

236
	Usage: dive,keys,othertagvalidation(s),endkeys,valuevalidationtags
237

238
Example #1
239

240
	map[string]string with validation tag "gt=0,dive,keys,eq=1|eq=2,endkeys,required"
241
	// gt=0 will be applied to the map itself
242
	// eq=1|eq=2 will be applied to the map keys
243
	// required will be applied to map values
244

245
Example #2
246

247
	map[[2]string]string with validation tag "gt=0,dive,keys,dive,eq=1|eq=2,endkeys,required"
248
	// gt=0 will be applied to the map itself
249
	// eq=1|eq=2 will be applied to each array element in the map keys
250
	// required will be applied to map values
251

252
# Required
253

254
This validates that the value is not the data types default zero value.
255
For numbers ensures value is not zero. For strings ensures value is
256
not "". For slices, maps, pointers, interfaces, channels and functions
257
ensures the value is not nil. For structs ensures value is not the zero value when using WithRequiredStructEnabled.
258

259
	Usage: required
260

261
# Required If
262

263
The field under validation must be present and not empty only if all
264
the other specified fields are equal to the value following the specified
265
field. For strings ensures value is not "". For slices, maps, pointers,
266
interfaces, channels and functions ensures the value is not nil. For structs ensures value is not the zero value.
267

268
	Usage: required_if
269

270
Examples:
271

272
	// require the field if the Field1 is equal to the parameter given:
273
	Usage: required_if=Field1 foobar
274

275
	// require the field if the Field1 and Field2 is equal to the value respectively:
276
	Usage: required_if=Field1 foo Field2 bar
277

278
# Required Unless
279

280
The field under validation must be present and not empty unless all
281
the other specified fields are equal to the value following the specified
282
field. For strings ensures value is not "". For slices, maps, pointers,
283
interfaces, channels and functions ensures the value is not nil. For structs ensures value is not the zero value.
284

285
	Usage: required_unless
286

287
Examples:
288

289
	// require the field unless the Field1 is equal to the parameter given:
290
	Usage: required_unless=Field1 foobar
291

292
	// require the field unless the Field1 and Field2 is equal to the value respectively:
293
	Usage: required_unless=Field1 foo Field2 bar
294

295
# Required With
296

297
The field under validation must be present and not empty only if any
298
of the other specified fields are present. For strings ensures value is
299
not "". For slices, maps, pointers, interfaces, channels and functions
300
ensures the value is not nil. For structs ensures value is not the zero value.
301

302
	Usage: required_with
303

304
Examples:
305

306
	// require the field if the Field1 is present:
307
	Usage: required_with=Field1
308

309
	// require the field if the Field1 or Field2 is present:
310
	Usage: required_with=Field1 Field2
311

312
# Required With All
313

314
The field under validation must be present and not empty only if all
315
of the other specified fields are present. For strings ensures value is
316
not "". For slices, maps, pointers, interfaces, channels and functions
317
ensures the value is not nil. For structs ensures value is not the zero value.
318

319
	Usage: required_with_all
320

321
Example:
322

323
	// require the field if the Field1 and Field2 is present:
324
	Usage: required_with_all=Field1 Field2
325

326
# Required Without
327

328
The field under validation must be present and not empty only when any
329
of the other specified fields are not present. For strings ensures value is
330
not "". For slices, maps, pointers, interfaces, channels and functions
331
ensures the value is not nil. For structs ensures value is not the zero value.
332

333
	Usage: required_without
334

335
Examples:
336

337
	// require the field if the Field1 is not present:
338
	Usage: required_without=Field1
339

340
	// require the field if the Field1 or Field2 is not present:
341
	Usage: required_without=Field1 Field2
342

343
# Required Without All
344

345
The field under validation must be present and not empty only when all
346
of the other specified fields are not present. For strings ensures value is
347
not "". For slices, maps, pointers, interfaces, channels and functions
348
ensures the value is not nil. For structs ensures value is not the zero value.
349

350
	Usage: required_without_all
351

352
Example:
353

354
	// require the field if the Field1 and Field2 is not present:
355
	Usage: required_without_all=Field1 Field2
356

357
# Excluded If
358

359
The field under validation must not be present or not empty only if all
360
the other specified fields are equal to the value following the specified
361
field. For strings ensures value is not "". For slices, maps, pointers,
362
interfaces, channels and functions ensures the value is not nil. For structs ensures value is not the zero value.
363

364
	Usage: excluded_if
365

366
Examples:
367

368
	// exclude the field if the Field1 is equal to the parameter given:
369
	Usage: excluded_if=Field1 foobar
370

371
	// exclude the field if the Field1 and Field2 is equal to the value respectively:
372
	Usage: excluded_if=Field1 foo Field2 bar
373

374
# Excluded Unless
375

376
The field under validation must not be present or empty unless all
377
the other specified fields are equal to the value following the specified
378
field. For strings ensures value is not "". For slices, maps, pointers,
379
interfaces, channels and functions ensures the value is not nil. For structs ensures value is not the zero value.
380

381
	Usage: excluded_unless
382

383
Examples:
384

385
	// exclude the field unless the Field1 is equal to the parameter given:
386
	Usage: excluded_unless=Field1 foobar
387

388
	// exclude the field unless the Field1 and Field2 is equal to the value respectively:
389
	Usage: excluded_unless=Field1 foo Field2 bar
390

391
# Is Default
392

393
This validates that the value is the default value and is almost the
394
opposite of required.
395

396
	Usage: isdefault
397

398
# Length
399

400
For numbers, length will ensure that the value is
401
equal to the parameter given. For strings, it checks that
402
the string length is exactly that number of characters. For slices,
403
arrays, and maps, validates the number of items.
404

405
Example #1
406

407
	Usage: len=10
408

409
Example #2 (time.Duration)
410

411
For time.Duration, len will ensure that the value is equal to the duration given
412
in the parameter.
413

414
	Usage: len=1h30m
415

416
# Maximum
417

418
For numbers, max will ensure that the value is
419
less than or equal to the parameter given. For strings, it checks
420
that the string length is at most that number of characters. For
421
slices, arrays, and maps, validates the number of items.
422

423
Example #1
424

425
	Usage: max=10
426

427
Example #2 (time.Duration)
428

429
For time.Duration, max will ensure that the value is less than or equal to the
430
duration given in the parameter.
431

432
	Usage: max=1h30m
433

434
# Minimum
435

436
For numbers, min will ensure that the value is
437
greater or equal to the parameter given. For strings, it checks that
438
the string length is at least that number of characters. For slices,
439
arrays, and maps, validates the number of items.
440

441
Example #1
442

443
	Usage: min=10
444

445
Example #2 (time.Duration)
446

447
For time.Duration, min will ensure that the value is greater than or equal to
448
the duration given in the parameter.
449

450
	Usage: min=1h30m
451

452
# Equals
453

454
For strings & numbers, eq will ensure that the value is
455
equal to the parameter given. For slices, arrays, and maps,
456
validates the number of items.
457

458
Example #1
459

460
	Usage: eq=10
461

462
Example #2 (time.Duration)
463

464
For time.Duration, eq will ensure that the value is equal to the duration given
465
in the parameter.
466

467
	Usage: eq=1h30m
468

469
# Not Equal
470

471
For strings & numbers, ne will ensure that the value is not
472
equal to the parameter given. For slices, arrays, and maps,
473
validates the number of items.
474

475
Example #1
476

477
	Usage: ne=10
478

479
Example #2 (time.Duration)
480

481
For time.Duration, ne will ensure that the value is not equal to the duration
482
given in the parameter.
483

484
	Usage: ne=1h30m
485

486
# One Of
487

488
For strings, ints, and uints, oneof will ensure that the value
489
is one of the values in the parameter.  The parameter should be
490
a list of values separated by whitespace. Values may be
491
strings or numbers. To match strings with spaces in them, include
492
the target string between single quotes.
493

494
	Usage: oneof=red green
495
	       oneof='red green' 'blue yellow'
496
	       oneof=5 7 9
497

498
# Greater Than
499

500
For numbers, this will ensure that the value is greater than the
501
parameter given. For strings, it checks that the string length
502
is greater than that number of characters. For slices, arrays
503
and maps it validates the number of items.
504

505
Example #1
506

507
	Usage: gt=10
508

509
Example #2 (time.Time)
510

511
For time.Time ensures the time value is greater than time.Now.UTC().
512

513
	Usage: gt
514

515
Example #3 (time.Duration)
516

517
For time.Duration, gt will ensure that the value is greater than the duration
518
given in the parameter.
519

520
	Usage: gt=1h30m
521

522
# Greater Than or Equal
523

524
Same as 'min' above. Kept both to make terminology with 'len' easier.
525

526
Example #1
527

528
	Usage: gte=10
529

530
Example #2 (time.Time)
531

532
For time.Time ensures the time value is greater than or equal to time.Now.UTC().
533

534
	Usage: gte
535

536
Example #3 (time.Duration)
537

538
For time.Duration, gte will ensure that the value is greater than or equal to
539
the duration given in the parameter.
540

541
	Usage: gte=1h30m
542

543
# Less Than
544

545
For numbers, this will ensure that the value is less than the parameter given.
546
For strings, it checks that the string length is less than that number of
547
characters. For slices, arrays, and maps it validates the number of items.
548

549
Example #1
550

551
	Usage: lt=10
552

553
Example #2 (time.Time)
554

555
For time.Time ensures the time value is less than time.Now.UTC().
556

557
	Usage: lt
558

559
Example #3 (time.Duration)
560

561
For time.Duration, lt will ensure that the value is less than the duration given
562
in the parameter.
563

564
	Usage: lt=1h30m
565

566
# Less Than or Equal
567

568
Same as 'max' above. Kept both to make terminology with 'len' easier.
569

570
Example #1
571

572
	Usage: lte=10
573

574
Example #2 (time.Time)
575

576
For time.Time ensures the time value is less than or equal to time.Now.UTC().
577

578
	Usage: lte
579

580
Example #3 (time.Duration)
581

582
For time.Duration, lte will ensure that the value is less than or equal to the
583
duration given in the parameter.
584

585
	Usage: lte=1h30m
586

587
# Field Equals Another Field
588

589
This will validate the field value against another fields value either within
590
a struct or passed in field.
591

592
Example #1:
593

594
	// Validation on Password field using:
595
	Usage: eqfield=ConfirmPassword
596

597
Example #2:
598

599
	// Validating by field:
600
	validate.VarWithValue(password, confirmpassword, "eqfield")
601

602
Field Equals Another Field (relative)
603

604
This does the same as eqfield except that it validates the field provided relative
605
to the top level struct.
606

607
	Usage: eqcsfield=InnerStructField.Field)
608

609
# Field Does Not Equal Another Field
610

611
This will validate the field value against another fields value either within
612
a struct or passed in field.
613

614
Examples:
615

616
	// Confirm two colors are not the same:
617
	//
618
	// Validation on Color field:
619
	Usage: nefield=Color2
620

621
	// Validating by field:
622
	validate.VarWithValue(color1, color2, "nefield")
623

624
Field Does Not Equal Another Field (relative)
625

626
This does the same as nefield except that it validates the field provided
627
relative to the top level struct.
628

629
	Usage: necsfield=InnerStructField.Field
630

631
# Field Greater Than Another Field
632

633
Only valid for Numbers, time.Duration and time.Time types, this will validate
634
the field value against another fields value either within a struct or passed in
635
field. usage examples are for validation of a Start and End date:
636

637
Example #1:
638

639
	// Validation on End field using:
640
	validate.Struct Usage(gtfield=Start)
641

642
Example #2:
643

644
	// Validating by field:
645
	validate.VarWithValue(start, end, "gtfield")
646

647
# Field Greater Than Another Relative Field
648

649
This does the same as gtfield except that it validates the field provided
650
relative to the top level struct.
651

652
	Usage: gtcsfield=InnerStructField.Field
653

654
# Field Greater Than or Equal To Another Field
655

656
Only valid for Numbers, time.Duration and time.Time types, this will validate
657
the field value against another fields value either within a struct or passed in
658
field. usage examples are for validation of a Start and End date:
659

660
Example #1:
661

662
	// Validation on End field using:
663
	validate.Struct Usage(gtefield=Start)
664

665
Example #2:
666

667
	// Validating by field:
668
	validate.VarWithValue(start, end, "gtefield")
669

670
# Field Greater Than or Equal To Another Relative Field
671

672
This does the same as gtefield except that it validates the field provided relative
673
to the top level struct.
674

675
	Usage: gtecsfield=InnerStructField.Field
676

677
# Less Than Another Field
678

679
Only valid for Numbers, time.Duration and time.Time types, this will validate
680
the field value against another fields value either within a struct or passed in
681
field. usage examples are for validation of a Start and End date:
682

683
Example #1:
684

685
	// Validation on End field using:
686
	validate.Struct Usage(ltfield=Start)
687

688
Example #2:
689

690
	// Validating by field:
691
	validate.VarWithValue(start, end, "ltfield")
692

693
# Less Than Another Relative Field
694

695
This does the same as ltfield except that it validates the field provided relative
696
to the top level struct.
697

698
	Usage: ltcsfield=InnerStructField.Field
699

700
# Less Than or Equal To Another Field
701

702
Only valid for Numbers, time.Duration and time.Time types, this will validate
703
the field value against another fields value either within a struct or passed in
704
field. usage examples are for validation of a Start and End date:
705

706
Example #1:
707

708
	// Validation on End field using:
709
	validate.Struct Usage(ltefield=Start)
710

711
Example #2:
712

713
	// Validating by field:
714
	validate.VarWithValue(start, end, "ltefield")
715

716
# Less Than or Equal To Another Relative Field
717

718
This does the same as ltefield except that it validates the field provided relative
719
to the top level struct.
720

721
	Usage: ltecsfield=InnerStructField.Field
722

723
# Field Contains Another Field
724

725
This does the same as contains except for struct fields. It should only be used
726
with string types. See the behavior of reflect.Value.String() for behavior on
727
other types.
728

729
	Usage: containsfield=InnerStructField.Field
730

731
# Field Excludes Another Field
732

733
This does the same as excludes except for struct fields. It should only be used
734
with string types. See the behavior of reflect.Value.String() for behavior on
735
other types.
736

737
	Usage: excludesfield=InnerStructField.Field
738

739
# Unique
740

741
For arrays & slices, unique will ensure that there are no duplicates.
742
For maps, unique will ensure that there are no duplicate values.
743
For slices of struct, unique will ensure that there are no duplicate values
744
in a field of the struct specified via a parameter.
745

746
	// For arrays, slices, and maps:
747
	Usage: unique
748

749
	// For slices of struct:
750
	Usage: unique=field
751

752
# Alpha Only
753

754
This validates that a string value contains ASCII alpha characters only
755

756
	Usage: alpha
757

758
# Alphanumeric
759

760
This validates that a string value contains ASCII alphanumeric characters only
761

762
	Usage: alphanum
763

764
# Alpha Unicode
765

766
This validates that a string value contains unicode alpha characters only
767

768
	Usage: alphaunicode
769

770
# Alphanumeric Unicode
771

772
This validates that a string value contains unicode alphanumeric characters only
773

774
	Usage: alphanumunicode
775

776
# Boolean
777

778
This validates that a string value can successfully be parsed into a boolean with strconv.ParseBool
779

780
	Usage: boolean
781

782
# Number
783

784
This validates that a string value contains number values only.
785
For integers or float it returns true.
786

787
	Usage: number
788

789
# Numeric
790

791
This validates that a string value contains a basic numeric value.
792
basic excludes exponents etc...
793
for integers or float it returns true.
794

795
	Usage: numeric
796

797
# Hexadecimal String
798

799
This validates that a string value contains a valid hexadecimal.
800

801
	Usage: hexadecimal
802

803
# Hexcolor String
804

805
This validates that a string value contains a valid hex color including
806
hashtag (#)
807

808
	Usage: hexcolor
809

810
# Lowercase String
811

812
This validates that a string value contains only lowercase characters. An empty string is not a valid lowercase string.
813

814
	Usage: lowercase
815

816
# Uppercase String
817

818
This validates that a string value contains only uppercase characters. An empty string is not a valid uppercase string.
819

820
	Usage: uppercase
821

822
# RGB String
823

824
This validates that a string value contains a valid rgb color
825

826
	Usage: rgb
827

828
# RGBA String
829

830
This validates that a string value contains a valid rgba color
831

832
	Usage: rgba
833

834
# HSL String
835

836
This validates that a string value contains a valid hsl color
837

838
	Usage: hsl
839

840
# HSLA String
841

842
This validates that a string value contains a valid hsla color
843

844
	Usage: hsla
845

846
# E.164 Phone Number String
847

848
This validates that a string value contains a valid E.164 Phone number
849
https://en.wikipedia.org/wiki/E.164 (ex. +1123456789)
850

851
	Usage: e164
852

853
# E-mail String
854

855
This validates that a string value contains a valid email
856
This may not conform to all possibilities of any rfc standard, but neither
857
does any email provider accept all possibilities.
858

859
	Usage: email
860

861
# JSON String
862

863
This validates that a string value is valid JSON
864

865
	Usage: json
866

867
# JWT String
868

869
This validates that a string value is a valid JWT
870

871
	Usage: jwt
872

873
# File
874

875
This validates that a string value contains a valid file path and that
876
the file exists on the machine.
877
This is done using os.Stat, which is a platform independent function.
878

879
	Usage: file
880

881
# Image path
882

883
This validates that a string value contains a valid file path and that
884
the file exists on the machine and is an image.
885
This is done using os.Stat and github.com/gabriel-vasile/mimetype
886

887
	Usage: image
888

889
# File Path
890

891
This validates that a string value contains a valid file path but does not
892
validate the existence of that file.
893
This is done using os.Stat, which is a platform independent function.
894

895
	Usage: filepath
896

897
# URL String
898

899
This validates that a string value contains a valid url
900
This will accept any url the golang request uri accepts but must contain
901
a schema for example http:// or rtmp://
902

903
	Usage: url
904

905
# URI String
906

907
This validates that a string value contains a valid uri
908
This will accept any uri the golang request uri accepts
909

910
	Usage: uri
911

912
# Urn RFC 2141 String
913

914
This validataes that a string value contains a valid URN
915
according to the RFC 2141 spec.
916

917
	Usage: urn_rfc2141
918

919
# Base64 String
920

921
This validates that a string value contains a valid base64 value.
922
Although an empty string is valid base64 this will report an empty string
923
as an error, if you wish to accept an empty string as valid you can use
924
this with the omitempty tag.
925

926
	Usage: base64
927

928
# Base64URL String
929

930
This validates that a string value contains a valid base64 URL safe value
931
according the RFC4648 spec.
932
Although an empty string is a valid base64 URL safe value, this will report
933
an empty string as an error, if you wish to accept an empty string as valid
934
you can use this with the omitempty tag.
935

936
	Usage: base64url
937

938
# Base64RawURL String
939

940
This validates that a string value contains a valid base64 URL safe value,
941
but without = padding, according the RFC4648 spec, section 3.2.
942
Although an empty string is a valid base64 URL safe value, this will report
943
an empty string as an error, if you wish to accept an empty string as valid
944
you can use this with the omitempty tag.
945

946
	Usage: base64url
947

948
# Bitcoin Address
949

950
This validates that a string value contains a valid bitcoin address.
951
The format of the string is checked to ensure it matches one of the three formats
952
P2PKH, P2SH and performs checksum validation.
953

954
	Usage: btc_addr
955

956
Bitcoin Bech32 Address (segwit)
957

958
This validates that a string value contains a valid bitcoin Bech32 address as defined
959
by bip-0173 (https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki)
960
Special thanks to Pieter Wuille for providng reference implementations.
961

962
	Usage: btc_addr_bech32
963

964
# Ethereum Address
965

966
This validates that a string value contains a valid ethereum address.
967
The format of the string is checked to ensure it matches the standard Ethereum address format.
968

969
	Usage: eth_addr
970

971
# Contains
972

973
This validates that a string value contains the substring value.
974

975
	Usage: contains=@
976

977
# Contains Any
978

979
This validates that a string value contains any Unicode code points
980
in the substring value.
981

982
	Usage: containsany=!@#?
983

984
# Contains Rune
985

986
This validates that a string value contains the supplied rune value.
987

988
	Usage: containsrune=@
989

990
# Excludes
991

992
This validates that a string value does not contain the substring value.
993

994
	Usage: excludes=@
995

996
# Excludes All
997

998
This validates that a string value does not contain any Unicode code
999
points in the substring value.
1000

1001
	Usage: excludesall=!@#?
1002

1003
# Excludes Rune
1004

1005
This validates that a string value does not contain the supplied rune value.
1006

1007
	Usage: excludesrune=@
1008

1009
# Starts With
1010

1011
This validates that a string value starts with the supplied string value
1012

1013
	Usage: startswith=hello
1014

1015
# Ends With
1016

1017
This validates that a string value ends with the supplied string value
1018

1019
	Usage: endswith=goodbye
1020

1021
# Does Not Start With
1022

1023
This validates that a string value does not start with the supplied string value
1024

1025
	Usage: startsnotwith=hello
1026

1027
# Does Not End With
1028

1029
This validates that a string value does not end with the supplied string value
1030

1031
	Usage: endsnotwith=goodbye
1032

1033
# International Standard Book Number
1034

1035
This validates that a string value contains a valid isbn10 or isbn13 value.
1036

1037
	Usage: isbn
1038

1039
# International Standard Book Number 10
1040

1041
This validates that a string value contains a valid isbn10 value.
1042

1043
	Usage: isbn10
1044

1045
# International Standard Book Number 13
1046

1047
This validates that a string value contains a valid isbn13 value.
1048

1049
	Usage: isbn13
1050

1051
# Universally Unique Identifier UUID
1052

1053
This validates that a string value contains a valid UUID. Uppercase UUID values will not pass - use `uuid_rfc4122` instead.
1054

1055
	Usage: uuid
1056

1057
# Universally Unique Identifier UUID v3
1058

1059
This validates that a string value contains a valid version 3 UUID.  Uppercase UUID values will not pass - use `uuid3_rfc4122` instead.
1060

1061
	Usage: uuid3
1062

1063
# Universally Unique Identifier UUID v4
1064

1065
This validates that a string value contains a valid version 4 UUID.  Uppercase UUID values will not pass - use `uuid4_rfc4122` instead.
1066

1067
	Usage: uuid4
1068

1069
# Universally Unique Identifier UUID v5
1070

1071
This validates that a string value contains a valid version 5 UUID.  Uppercase UUID values will not pass - use `uuid5_rfc4122` instead.
1072

1073
	Usage: uuid5
1074

1075
# Universally Unique Lexicographically Sortable Identifier ULID
1076

1077
This validates that a string value contains a valid ULID value.
1078

1079
	Usage: ulid
1080

1081
# ASCII
1082

1083
This validates that a string value contains only ASCII characters.
1084
NOTE: if the string is blank, this validates as true.
1085

1086
	Usage: ascii
1087

1088
# Printable ASCII
1089

1090
This validates that a string value contains only printable ASCII characters.
1091
NOTE: if the string is blank, this validates as true.
1092

1093
	Usage: printascii
1094

1095
# Multi-Byte Characters
1096

1097
This validates that a string value contains one or more multibyte characters.
1098
NOTE: if the string is blank, this validates as true.
1099

1100
	Usage: multibyte
1101

1102
# Data URL
1103

1104
This validates that a string value contains a valid DataURI.
1105
NOTE: this will also validate that the data portion is valid base64
1106

1107
	Usage: datauri
1108

1109
# Latitude
1110

1111
This validates that a string value contains a valid latitude.
1112

1113
	Usage: latitude
1114

1115
# Longitude
1116

1117
This validates that a string value contains a valid longitude.
1118

1119
	Usage: longitude
1120

1121
# Social Security Number SSN
1122

1123
This validates that a string value contains a valid U.S. Social Security Number.
1124

1125
	Usage: ssn
1126

1127
# Internet Protocol Address IP
1128

1129
This validates that a string value contains a valid IP Address.
1130

1131
	Usage: ip
1132

1133
# Internet Protocol Address IPv4
1134

1135
This validates that a string value contains a valid v4 IP Address.
1136

1137
	Usage: ipv4
1138

1139
# Internet Protocol Address IPv6
1140

1141
This validates that a string value contains a valid v6 IP Address.
1142

1143
	Usage: ipv6
1144

1145
# Classless Inter-Domain Routing CIDR
1146

1147
This validates that a string value contains a valid CIDR Address.
1148

1149
	Usage: cidr
1150

1151
# Classless Inter-Domain Routing CIDRv4
1152

1153
This validates that a string value contains a valid v4 CIDR Address.
1154

1155
	Usage: cidrv4
1156

1157
# Classless Inter-Domain Routing CIDRv6
1158

1159
This validates that a string value contains a valid v6 CIDR Address.
1160

1161
	Usage: cidrv6
1162

1163
# Transmission Control Protocol Address TCP
1164

1165
This validates that a string value contains a valid resolvable TCP Address.
1166

1167
	Usage: tcp_addr
1168

1169
# Transmission Control Protocol Address TCPv4
1170

1171
This validates that a string value contains a valid resolvable v4 TCP Address.
1172

1173
	Usage: tcp4_addr
1174

1175
# Transmission Control Protocol Address TCPv6
1176

1177
This validates that a string value contains a valid resolvable v6 TCP Address.
1178

1179
	Usage: tcp6_addr
1180

1181
# User Datagram Protocol Address UDP
1182

1183
This validates that a string value contains a valid resolvable UDP Address.
1184

1185
	Usage: udp_addr
1186

1187
# User Datagram Protocol Address UDPv4
1188

1189
This validates that a string value contains a valid resolvable v4 UDP Address.
1190

1191
	Usage: udp4_addr
1192

1193
# User Datagram Protocol Address UDPv6
1194

1195
This validates that a string value contains a valid resolvable v6 UDP Address.
1196

1197
	Usage: udp6_addr
1198

1199
# Internet Protocol Address IP
1200

1201
This validates that a string value contains a valid resolvable IP Address.
1202

1203
	Usage: ip_addr
1204

1205
# Internet Protocol Address IPv4
1206

1207
This validates that a string value contains a valid resolvable v4 IP Address.
1208

1209
	Usage: ip4_addr
1210

1211
# Internet Protocol Address IPv6
1212

1213
This validates that a string value contains a valid resolvable v6 IP Address.
1214

1215
	Usage: ip6_addr
1216

1217
# Unix domain socket end point Address
1218

1219
This validates that a string value contains a valid Unix Address.
1220

1221
	Usage: unix_addr
1222

1223
# Media Access Control Address MAC
1224

1225
This validates that a string value contains a valid MAC Address.
1226

1227
	Usage: mac
1228

1229
Note: See Go's ParseMAC for accepted formats and types:
1230

1231
	http://golang.org/src/net/mac.go?s=866:918#L29
1232

1233
# Hostname RFC 952
1234

1235
This validates that a string value is a valid Hostname according to RFC 952 https://tools.ietf.org/html/rfc952
1236

1237
	Usage: hostname
1238

1239
# Hostname RFC 1123
1240

1241
This validates that a string value is a valid Hostname according to RFC 1123 https://tools.ietf.org/html/rfc1123
1242

1243
	Usage: hostname_rfc1123 or if you want to continue to use 'hostname' in your tags, create an alias.
1244

1245
Full Qualified Domain Name (FQDN)
1246

1247
This validates that a string value contains a valid FQDN.
1248

1249
	Usage: fqdn
1250

1251
# HTML Tags
1252

1253
This validates that a string value appears to be an HTML element tag
1254
including those described at https://developer.mozilla.org/en-US/docs/Web/HTML/Element
1255

1256
	Usage: html
1257

1258
# HTML Encoded
1259

1260
This validates that a string value is a proper character reference in decimal
1261
or hexadecimal format
1262

1263
	Usage: html_encoded
1264

1265
# URL Encoded
1266

1267
This validates that a string value is percent-encoded (URL encoded) according
1268
to https://tools.ietf.org/html/rfc3986#section-2.1
1269

1270
	Usage: url_encoded
1271

1272
# Directory
1273

1274
This validates that a string value contains a valid directory and that
1275
it exists on the machine.
1276
This is done using os.Stat, which is a platform independent function.
1277

1278
	Usage: dir
1279

1280
# Directory Path
1281

1282
This validates that a string value contains a valid directory but does
1283
not validate the existence of that directory.
1284
This is done using os.Stat, which is a platform independent function.
1285
It is safest to suffix the string with os.PathSeparator if the directory
1286
may not exist at the time of validation.
1287

1288
	Usage: dirpath
1289

1290
# HostPort
1291

1292
This validates that a string value contains a valid DNS hostname and port that
1293
can be used to valiate fields typically passed to sockets and connections.
1294

1295
	Usage: hostname_port
1296

1297
# Datetime
1298

1299
This validates that a string value is a valid datetime based on the supplied datetime format.
1300
Supplied format must match the official Go time format layout as documented in https://golang.org/pkg/time/
1301

1302
	Usage: datetime=2006-01-02
1303

1304
# Iso3166-1 alpha-2
1305

1306
This validates that a string value is a valid country code based on iso3166-1 alpha-2 standard.
1307
see: https://www.iso.org/iso-3166-country-codes.html
1308

1309
	Usage: iso3166_1_alpha2
1310

1311
# Iso3166-1 alpha-3
1312

1313
This validates that a string value is a valid country code based on iso3166-1 alpha-3 standard.
1314
see: https://www.iso.org/iso-3166-country-codes.html
1315

1316
	Usage: iso3166_1_alpha3
1317

1318
# Iso3166-1 alpha-numeric
1319

1320
This validates that a string value is a valid country code based on iso3166-1 alpha-numeric standard.
1321
see: https://www.iso.org/iso-3166-country-codes.html
1322

1323
	Usage: iso3166_1_alpha3
1324

1325
# BCP 47 Language Tag
1326

1327
This validates that a string value is a valid BCP 47 language tag, as parsed by language.Parse.
1328
More information on https://pkg.go.dev/golang.org/x/text/language
1329

1330
	Usage: bcp47_language_tag
1331

1332
BIC (SWIFT code)
1333

1334
This validates that a string value is a valid Business Identifier Code (SWIFT code), defined in ISO 9362.
1335
More information on https://www.iso.org/standard/60390.html
1336

1337
	Usage: bic
1338

1339
# RFC 1035 label
1340

1341
This validates that a string value is a valid dns RFC 1035 label, defined in RFC 1035.
1342
More information on https://datatracker.ietf.org/doc/html/rfc1035
1343

1344
	Usage: dns_rfc1035_label
1345

1346
# TimeZone
1347

1348
This validates that a string value is a valid time zone based on the time zone database present on the system.
1349
Although empty value and Local value are allowed by time.LoadLocation golang function, they are not allowed by this validator.
1350
More information on https://golang.org/pkg/time/#LoadLocation
1351

1352
	Usage: timezone
1353

1354
# Semantic Version
1355

1356
This validates that a string value is a valid semver version, defined in Semantic Versioning 2.0.0.
1357
More information on https://semver.org/
1358

1359
	Usage: semver
1360

1361
# CVE Identifier
1362

1363
This validates that a string value is a valid cve id, defined in cve mitre.
1364
More information on https://cve.mitre.org/
1365

1366
	Usage: cve
1367

1368
# Credit Card
1369

1370
This validates that a string value contains a valid credit card number using Luhn algorithm.
1371

1372
	Usage: credit_card
1373

1374
# Luhn Checksum
1375

1376
	Usage: luhn_checksum
1377

1378
This validates that a string or (u)int value contains a valid checksum using the Luhn algorithm.
1379

1380
# MongoDb ObjectID
1381

1382
This validates that a string is a valid 24 character hexadecimal string.
1383

1384
	Usage: mongodb
1385

1386
# Cron
1387

1388
This validates that a string value contains a valid cron expression.
1389

1390
	Usage: cron
1391

1392
# SpiceDb ObjectID/Permission/Object Type
1393

1394
This validates that a string is valid for use with SpiceDb for the indicated purpose. If no purpose is given, a purpose of 'id' is assumed.
1395

1396
	Usage: spicedb=id|permission|type
1397

1398
# Alias Validators and Tags
1399

1400
Alias Validators and Tags
1401
NOTE: When returning an error, the tag returned in "FieldError" will be
1402
the alias tag unless the dive tag is part of the alias. Everything after the
1403
dive tag is not reported as the alias tag. Also, the "ActualTag" in the before
1404
case will be the actual tag within the alias that failed.
1405

1406
Here is a list of the current built in alias tags:
1407

1408
	"iscolor"
1409
		alias is "hexcolor|rgb|rgba|hsl|hsla" (Usage: iscolor)
1410
	"country_code"
1411
		alias is "iso3166_1_alpha2|iso3166_1_alpha3|iso3166_1_alpha_numeric" (Usage: country_code)
1412

1413
Validator notes:
1414

1415
	regex
1416
		a regex validator won't be added because commas and = signs can be part
1417
		of a regex which conflict with the validation definitions. Although
1418
		workarounds can be made, they take away from using pure regex's.
1419
		Furthermore it's quick and dirty but the regex's become harder to
1420
		maintain and are not reusable, so it's as much a programming philosophy
1421
		as anything.
1422

1423
		In place of this new validator functions should be created; a regex can
1424
		be used within the validator function and even be precompiled for better
1425
		efficiency within regexes.go.
1426

1427
		And the best reason, you can submit a pull request and we can keep on
1428
		adding to the validation library of this package!
1429

1430
# Non standard validators
1431

1432
A collection of validation rules that are frequently needed but are more
1433
complex than the ones found in the baked in validators.
1434
A non standard validator must be registered manually like you would
1435
with your own custom validation functions.
1436

1437
Example of registration and use:
1438

1439
	type Test struct {
1440
		TestField string `validate:"yourtag"`
1441
	}
1442

1443
	t := &Test{
1444
		TestField: "Test"
1445
	}
1446

1447
	validate := validator.New()
1448
	validate.RegisterValidation("yourtag", validators.NotBlank)
1449

1450
Here is a list of the current non standard validators:
1451

1452
	NotBlank
1453
		This validates that the value is not blank or with length zero.
1454
		For strings ensures they do not contain only spaces. For channels, maps, slices and arrays
1455
		ensures they don't have zero length. For others, a non empty value is required.
1456

1457
		Usage: notblank
1458

1459
# Panics
1460

1461
This package panics when bad input is provided, this is by design, bad code like
1462
that should not make it to production.
1463

1464
	type Test struct {
1465
		TestField string `validate:"nonexistantfunction=1"`
1466
	}
1467

1468
	t := &Test{
1469
		TestField: "Test"
1470
	}
1471

1472
	validate.Struct(t) // this will panic
1473
*/
1474
package validator
1475

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.