标准库

package validator

import “gopkg.in/go-playground/validator.v9”

Package validator 基于标签对结构和单个字段实现值验证.

它还可以处理嵌套结构的跨字段和跨结构验证,并具有深入研究任何类型的数组和映射的能力。

查看更多示例 https://github.com/go-playground/validator/tree/master/_examples

验证函数返回类型错误

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

https://golang.org/pkg/os/#Open. The authors return type “error” to avoid the issue discussed in the following, where err is always != nil:

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

Validator only InvalidValidationError for bad validation input, nil or ValidationErrors as type error; 因此,在您的代码中,您所需要做的就是检查 err 是否为 nil, 以及检查错误是否为InvalidValidationError(如果有必要,大多数情况下不是),请像这样将其强制转换为ValidationErrors类型错误(validator.ValidationErrors)

自定义验证功能

可以添加自定义验证功能。

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// Structure
func customFunc(fl validator.FieldLevel) bool {

	if fl.Field().String() == "invalid" {
		return false
	}

	return true
}

validate.RegisterValidation("custom tag name", customFunc)
//注意:使用与现有功能相同的标记名称
//将覆盖现有功能

跨field验证

跨field验证可以通过以下标签完成:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
- eqfield
- nefield
- gtfield
- gtefield
- ltfield
- ltefield
- eqcsfield
- necsfield
- gtcsfield
- gtecsfield
- ltcsfield
- ltecsfield

如果需要某些自定义跨域验证,则可以使用自定义验证来完成。

为什么不只具有跨域验证标签(即仅eqcsfield而不是eqfield)?

原因是效率。如果要检查同一结构中的字段,则“ eqfield”仅需在同一结构(1级)上找到该字段。但是,如果我们使用“ eqcsfield”,则可能会降低多个级别。例:

 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
type Inner struct {
	StartDate time.Time
}

type Outer struct {
	InnerStructField *Inner
	CreatedAt time.Time      `validate:"ltecsfield=InnerStructField.StartDate"`
}

now := time.Now()

inner := &Inner{
	StartDate: now,
}

outer := &Outer{
	InnerStructField: inner,
	CreatedAt: now,
}

errs := validate.Struct(outer)

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

多个validate

字段上的多个validate将按照定义的顺序进行处理。例:

1
2
3
4
5
type Test struct {
	Field `validate:"max=10,min=1"`
}

// max will be checked then min

库不处理无效的验证器定义。例:

1
2
3
4
type Test struct {
	Field `validate:"min=10,max=0"`
}
// this definition of min max will never succeed

使用验证标签

跨field验证仅比较同一结构上的字段。如果需要跨field+跨struct验证,则应实现自己的自定义validator。

逗号(“,”)是验证标签的默认分隔符。如果希望在参数中包含逗号(即excludesall =,),则需要使用UTF-8十六进制表示形式0x2C,在代码中将其替换为逗号,因此以上内容将变为excludesall = 0x2C。

1
2
3
4
type Test struct {
	Field `validate:"excludesall=,"`    // BAD! Do not include a comma.
	Field `validate:"excludesall=0x2C"` // GOOD! Use the UTF-8 hex representation.
}

管道(“ |”)是’或’验证标签的分隔符。如果希望在参数中包含管道,即excludesall = | 您将需要使用UTF-8十六进制表示形式0x7C,在代码中将其替换为管道,因此以上内容将变为excludesall = 0x7C

1
2
3
4
type Test struct {
	Field `validate:"excludesall=|"`    // BAD! Do not include a a pipe!
	Field `validate:"excludesall=0x7C"` // GOOD! Use the UTF-8 hex representation.
}

Alias Validators and Tags

注意:返回错误时,在“FieldError”中返回的标签将是别名标签,除非dive标签是别名的一部分。dive标签之后的所有内容均不会报告为别名标签。同样,在前面的情况下,“ ActualTag”将是失败的别名中的实际标签。

这是当前内置别名标签的列表:

1
2
"iscolor"
	alias is "hexcolor|rgb|rgba|hsl|hsla" (Usage: iscolor)

正则表达式标签

不会添加正则表达式验证器,因为逗号和=符号可能是与验证定义冲突的正则表达式的一部分。 尽管可以采取解决方法,但它们不能使用纯正则表达式。 此外,它既快速又肮脏,正则表达式变得更难维护且不可重用,因此它与任何东西一样,都是编程哲学。

代替此新的验证器功能,应创建自定义验证函数; regex可以在验证函数中使用,甚至可以在regexes.go中进行预编译以提高效率。最好的原因是,您可以提交请求请求,我们可以继续添加到此程序包的验证库中!

Panics

当提供错误的输入时,此程序包会panic,这是设计使然,这样的错误代码不应使其投入生产。

1
2
3
4
5
6
7
8
9
type Test struct {
	TestField string `validate:"nonexistantfunction=1"`
}

t := &Test{
	TestField: "Test"
}

validate.Struct(t) // this will panic

Non standard validators

我们经常需要比在验证器中发现的验证规则更复杂的验证规则的集合。非标准验证器必须使用您喜欢的任何标签手动注册。请参阅下面的注册和使用示例。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
type Test struct {
	TestField string `validate:"yourtag"`
}

t := &Test{
	TestField: "Test"
}

validate := validator.New()
validate.RegisterValidation("yourtag", validations.ValidatorName)

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

    Usage: notblank

type CustomTypeFunc

1
type CustomTypeFunc func(field reflect.Value) interface{}

CustomTypeFunc允许重写或添加自定义字段类型处理程序函数field =类型的字段值以返回待验证的值

示例:

sql drive中的validator

请参见https://golang.org/src/database/sql/driver/types.go ?s = 1210:1293#L29

type FieldError

 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
type FieldError interface {

    // returns the validation tag that failed. if the
    // validation was an alias, this will return the
    // alias name and not the underlying tag that failed.
    //
    // eg. alias "iscolor": "hexcolor|rgb|rgba|hsl|hsla"
    // will return "iscolor"
    Tag() string

    // returns the validation tag that failed, even if an
    // alias the actual tag within the alias will be returned.
    // If an 'or' validation fails the entire or will be returned.
    //
    // eg. alias "iscolor": "hexcolor|rgb|rgba|hsl|hsla"
    // will return "hexcolor|rgb|rgba|hsl|hsla"
    ActualTag() string

    // returns the namespace for the field error, with the tag
    // name taking precedence over the fields actual name.
    //
    // eg. JSON name "User.fname"
    //
    // See StructNamespace() for a version that returns actual names.
    //
    // NOTE: this field can be blank when validating a single primitive field
    // using validate.Field(...) as there is no way to extract it's name
    Namespace() string

    // returns the namespace for the field error, with the fields
    // actual name.
    //
    // eq. "User.FirstName" see Namespace for comparison
    //
    // NOTE: this field can be blank when validating a single primitive field
    // using validate.Field(...) as there is no way to extract it's name
    StructNamespace() string

    // returns the fields name with the tag name taking precedence over the
    // fields actual name.
    //
    // eq. JSON name "fname"
    // see StructField for comparison
    Field() string

    // returns the fields actual name from the struct, when able to determine.
    //
    // eq.  "FirstName"
    // see Field for comparison
    StructField() string

    // returns the actual fields value in case needed for creating the error
    // message
    Value() interface{}

    // returns the param value, in string form for comparison; this will also
    // help with generating an error message
    Param() string

    // Kind returns the Field's reflect Kind
    //
    // eg. time.Time's kind is a struct
    Kind() reflect.Kind

    // Type returns the Field's reflect Type
    //
    // // eg. time.Time's type is time.Time
    Type() reflect.Type

    // returns the FieldError's translated error
    // from the provided 'ut.Translator' and registered 'TranslationFunc'
    //
    // NOTE: if no registered translator can be found it returns the same as
    // calling fe.Error()
    Translate(ut ut.Translator) string
}

FieldError包含获取错误详细信息的所有函数

 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
type FieldLevel
type FieldLevel interface {

    // returns the top level struct, if any
    Top() reflect.Value

    // returns the current fields parent struct, if any or
    // the comparison value if called 'VarWithValue'
    Parent() reflect.Value

    // returns current field for validation
    Field() reflect.Value

    // returns the field's name with the tag
    // name taking precedence over the fields actual name.
    FieldName() string

    // returns the struct field's name
    StructFieldName() string

    // returns param for validation against current field
    Param() string

    // ExtractType gets the actual underlying type of field value.
    // It will dive into pointers, customTypes and return you the
    // underlying value and it's kind.
    ExtractType(field reflect.Value) (value reflect.Value, kind reflect.Kind, nullable bool)

    // traverses the parent struct to retrieve a specific field denoted by the provided namespace
    // in the param and returns the field, field kind and whether is was successful in retrieving
    // the field at all.
    //
    // NOTE: when not successful ok will be false, this can happen when a nested struct is nil and so the field
    // could not be retrieved because it didn't exist.
    //
    // Deprecated: Use GetStructFieldOK2() instead which also return if the value is nullable.
    GetStructFieldOK() (reflect.Value, reflect.Kind, bool)

    // GetStructFieldOKAdvanced is the same as GetStructFieldOK except that it accepts the parent struct to start looking for
    // the field and namespace allowing more extensibility for validators.
    //
    // Deprecated: Use GetStructFieldOKAdvanced2() instead which also return if the value is nullable.
    GetStructFieldOKAdvanced(val reflect.Value, namespace string) (reflect.Value, reflect.Kind, bool)

    // traverses the parent struct to retrieve a specific field denoted by the provided namespace
    // in the param and returns the field, field kind, if it's a nullable type and whether is was successful in retrieving
    // the field at all.
    //
    // NOTE: when not successful ok will be false, this can happen when a nested struct is nil and so the field
    // could not be retrieved because it didn't exist.
    GetStructFieldOK2() (reflect.Value, reflect.Kind, bool, bool)

    // GetStructFieldOKAdvanced is the same as GetStructFieldOK except that it accepts the parent struct to start looking for
    // the field and namespace allowing more extensibility for validators.
    GetStructFieldOKAdvanced2(val reflect.Value, namespace string) (reflect.Value, reflect.Kind, bool, bool)
}

FieldLevel包含所有信息和帮助程序功能以验证字段

type FilterFunc

1
type FilterFunc func(ns []byte) bool

FilterFunc是用于使用StructFiltered(…)函数过滤字段的类型。从验证中过滤/跳过字段中返回真实结果

type Func

1
type Func func(fl FieldLevel) bool

Func接受FieldLevel接口以满足所有验证需求。验证成功时,返回值应为true。

type FuncCtx

1
type FuncCtx func(ctx context.Context, fl FieldLevel) bool

FuncCtx接受context.Context和FieldLevel接口来满足所有验证需求。验证成功时,返回值应为true。

type InvalidValidationError

1
2
3
type InvalidValidationError struct {
    Type reflect.Type
}

InvaStruct,StructExcept,StructPartial或Field的无效参数。

func (*InvalidValidationError) Error

1
func (e *InvalidValidationError) Error() string

Error返回InvalidValidationError消息

type RegisterTranslationsFunc

1
type RegisterTranslationsFunc func(ut ut.Translator) error

RegisterTranslationsFunc允许注册“ ut.Translator”的翻译,以在“TranslationFunc”中使用

type StructLevel

 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
type StructLevel interface {
    // returns the main validation object, in case one wants to call validations internally.
    // this is so you don't have to use anonymous functions to get access to the validate
    // instance.
    Validator() *Validate

    // returns the top level struct, if any
    Top() reflect.Value

    // returns the current fields parent struct, if any
    Parent() reflect.Value

    // returns the current struct.
    Current() reflect.Value

    // ExtractType gets the actual underlying type of field value.
    // It will dive into pointers, customTypes and return you the
    // underlying value and its kind.
    ExtractType(field reflect.Value) (value reflect.Value, kind reflect.Kind, nullable bool)

    // reports an error just by passing the field and tag information
    //
    // NOTES:
    //
    // fieldName and altName get appended to the existing namespace that
    // validator is on. e.g. pass 'FirstName' or 'Names[0]' depending
    // on the nesting
    //
    // tag can be an existing validation tag or just something you make up
    // and process on the flip side it's up to you.
    ReportError(field interface{}, fieldName, structFieldName string, tag, param string)

    // reports an error just by passing ValidationErrors
    //
    // NOTES:
    //
    // relativeNamespace and relativeActualNamespace get appended to the
    // existing namespace that validator is on.
    // e.g. pass 'User.FirstName' or 'Users[0].FirstName' depending
    // on the nesting. most of the time they will be blank, unless you validate
    // at a level lower the the current field depth
    ReportValidationErrors(relativeNamespace, relativeActualNamespace string, errs ValidationErrors)
}

StructLevel包含用于验证结构的所有信息和辅助函数

type StructLevelFunc

1
type StructLevelFunc func(sl StructLevel)

StructLevelFunc接受结构级别验证所需的所有值

type StructLevelFuncCtx

1
type StructLevelFuncCtx func(ctx context.Context, sl StructLevel)

StructLevelFuncCtx接受结构级别验证所需的所有值,但也允许通过context.Context传递上下文验证信息。

type TagNameFunc

1
type TagNameFunc func(field reflect.StructField) string

TagNameFunc允许添加自定义标签名称解析器

type TranslationFunc

1
type TranslationFunc func(ut ut.Translator, fe FieldError) string

TranslationFunc是用于注册或覆盖自定义翻译的函数类型

type Validate

1
2
3
type Validate struct {
// contains filtered or unexported fields
}

Validate包含验证器设置和缓存

func New

1
func New() *Validate

New返回一个默认值“validate”的新实例。

func (*Validate) RegisterAlias

1
func (v *Validate) RegisterAlias(alias, tags string)

RegisterAlias注册单个验证标签的映射,该映射定义一组通用或复杂的验证集,以简化向结构添加验证的过程。

注意:此函数不是线程安全的,因此应在进行任何验证之前先将它们全部注册

func (*Validate) RegisterCustomTypeFunc

1
func (v *Validate) RegisterCustomTypeFunc(fn CustomTypeFunc, types ...interface{})

RegisterCustomTypeFunc针对多种类型注册CustomTypeFunc

注意:此方法不是线程安全的,因此应在进行任何验证之前先将它们全部注册

func (*Validate) RegisterStructValidation

1
func (v *Validate) RegisterStructValidation(fn StructLevelFunc, types ...interface{})

RegisterStructValidation针对多种类型注册StructLevelFunc。

注意:-此方法不是线程安全的,因此应在进行任何验证之前先将它们全部注册

func (*Validate) RegisterStructValidationCtx

1
func (v *Validate) RegisterStructValidationCtx(fn StructLevelFuncCtx, types ...interface{})

RegisterStructValidationCtx针对多种类型注册StructLevelFuncCtx,并允许通过context.Context传递上下文验证信息。

注意:-此方法不是线程安全的,因此应在进行任何验证之前先将它们全部注册

func (*Validate) RegisterTagNameFunc

1
func (v *Validate) RegisterTagNameFunc(fn TagNameFunc)

RegisterTagNameFunc注册一个函数来获取StructFields的备用名称。

例如。使用为JSON表示结构指定的名称,而不是普通的Go字段名称:

1
2
3
4
5
6
7
validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
    name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
    if name == "-" {
        return ""
    }
    return name
})

func (*Validate) RegisterTranslation

1
func (v *Validate) RegisterTranslation(tag string, trans ut.Translator, registerFn,RegisterTranslationsFunc, translationFn TranslationFunc) (err error)

RegisterTranslation根据提供的标签注册翻译。

func (*Validate) RegisterValidation

1
2
func (v *Validate) RegisterValidation(tag string, fn Func, callValidationEvenIfNull ...bool)
 error

RegisterValidation使用给定标签添加验证

注意:-如果密钥已经存在,则先前的验证功能将被替换。-此方法不是线程安全的,因此应在进行任何验证之前将其全部注册

func (*Validate) RegisterValidationCtx

1
2
func (v *Validate) RegisterValidationCtx(tag string, fn FuncCtx, callValidationEvenIfNull
...bool) error

RegisterValidationCtx的功能与RegisterValidation相同,它接受FuncCtx验证并允许使用context.Context验证。

func (*Validate) SetTagName

1
func (v *Validate) SetTagName(name string)

SetTagName允许更改默认标签名称“validate”

func (*Validate) Struct

1
func (v *Validate) Struct(s interface{}) error

除非另有说明,否则Struct会验证结构的公开字段,并自动验证嵌套的结构。

对于传入的错误值,它返回InvalidValidationError,否则返回nil或ValidationErrors作为错误。如果错误不为零,则需要声明错误。err.(validator.ValidationErrors)访问错误数组。

func (*Validate) StructCtx

1
func (v *Validate) StructCtx(ctx context.Context, s interface{}) (err error)

除非另行指定,否则StructCtx会验证暴露的结构体的结构,并自动验证嵌套的结构体,除非另外指定,并且还允许传递context.Context作为上下文验证信息。

对于传入的错误值,它返回InvalidValidationError,否则返回nil或ValidationErrors作为错误。如果错误不为零,则需要声明错误。err.(validator.ValidationErrors)访问错误数组。

func (*Validate) StructExcept

1
func (v *Validate) StructExcept(s interface{}, fields ...string) error

StructExcept会验证除传入字段外的所有其他字段。可以相对于所提供的结构(即NestedStruct.Field或NestedArrayField [0] .Struct.Name)以命名空间的方式提供字段。

对于传入的错误值,它返回InvalidValidationError,否则返回nil或ValidationErrors作为错误。如果错误不为零,则需要声明错误。err.(validator.ValidationErrors)访问错误数组。

func (*Validate) StructExceptCtx

1
2
func (v *Validate) StructExceptCtx(ctx context.Context, s interface{}, fields ...string)
(err error)

StructExceptCtx会验证除传入字段外的所有字段,并允许通过上下文传递上下文验证验证信息。可以相对于所提供的结构,即NestedStruct.Field或NestedArrayField [0] .Struct.Name,以命名空间的方式提供上下文字段。

对于传入的错误值,它返回InvalidValidationError,否则返回nil或ValidationErrors作为错误。如果错误不为零,则需要声明错误。err.(validator.ValidationErrors)访问错误数组。

func (*Validate) StructFiltered

1
func (v *Validate) StructFiltered(s interface{}, fn FilterFunc) error

除非另有说明,否则StructFiltered会验证结构公开的字段,这些字段通过FilterFunc检查并自动验证嵌套的结构。

对于传入的错误值,它返回InvalidValidationError,否则返回nil或ValidationErrors作为错误。如果错误不为零,则需要声明错误。err.(validator.ValidationErrors)访问错误数组。

func (*Validate) StructFilteredCtx

1
2
func (v *Validate) StructFilteredCtx(ctx context.Context, s interface{}, fn FilterFunc)
(err error)

除非另有说明,否则StructFilteredCtx会验证结构公开的字段,这些字段通过FilterFunc检查并自动验证嵌套的结构,除非另有说明,并且还允许通过context传递上下文验证信息。

对于传入的错误值,它返回InvalidValidationError,否则返回nil或ValidationErrors作为错误。如果错误不为零,则需要声明错误。err.(validator.ValidationErrors)访问错误数组。

func (*Validate) StructPartial

1
func (v *Validate) StructPartial(s interface{}, fields ...string) error

StructPartial仅验证传入的字段,而忽略所有其他字段。可以相对于所提供的结构以命名空间的方式提供字段。NestedStruct.Field或NestedArrayField [0] .Struct.Name

对于传入的错误值,它返回InvalidValidationError,否则返回nil或ValidationErrors作为错误。如果错误不为零,则需要声明错误。err.(validator.ValidationErrors)访问错误数组。

func (*Validate) StructPartialCtx

1
2
func (v *Validate) StructPartialCtx(ctx context.Context, s interface{}, fields ...string)
(err error)

StructPartialCtx仅验证传入的字段,而忽略所有其他字段,并允许通过context传递上下文验证验证信息。Context字段可以相对于所提供的结构以命名空间的方式提供。NestedStruct.Field或NestedArrayField [0] .Struct.Name

对于传入的错误值,它返回InvalidValidationError,否则返回nil或ValidationErrors作为错误。如果错误不为零,则需要声明错误。err.(validator.ValidationErrors)访问错误数组。

func (*Validate) Var

1
func (v *Validate) Var(field interface{}, tag string) error

Var使用标记样式验证来验证单个变量。例如

1
2
var i int
validate.Var(i, "gt=1,lt=10")

警告:可以传递结构进行验证,例如。time.Time是一个结构,或者您具有自定义类型并注册了自定义类型处理程序,因此必须允许它;但是,如果尝试验证要传递给“ validate.Struct”的结构,则会发生无法预料的验证

对于传入的错误值,它返回InvalidValidationError,否则返回nil或ValidationErrors作为错误。如果错误不为零,则需要声明错误。err.(validator.ValidationErrors)访问错误数组。 validate Array, Slice and maps fields which may contain more than one error

func (*Validate) VarCtx

1
func (v *Validate) VarCtx(ctx context.Context, field interface{}, tag string) (err error)

Var使用标记样式验证来验证单个变量。并允许通过context.Context传递上下文验证验证信息。例如

1
2
var i int
validate.Var(i, "gt=1,lt=10")

警告:可以传递结构进行验证,例如。time.Time是一个结构,或者您具有自定义类型并注册了自定义类型处理程序,因此必须允许它;但是,如果尝试验证要传递给“ validate.Struct”的结构,则会发生无法预料的验证

对于传入的错误值,它返回InvalidValidationError,否则返回nil或ValidationErrors作为错误。如果错误不为零,则需要声明错误。err.(validator.ValidationErrors)访问错误数组。 validate Array, Slice and maps fields which may contain more than one error

func (*Validate) VarWithValue

1
func (v *Validate) VarWithValue(field interface{}, other interface{}, tag string) error

VarWithValue使用标签样式验证(例如)针对另一个变量/字段的值来验证单个变量。

1
2
3
s1 := "abcd"
s2 := "abcd"
validate.VarWithValue(s1, s2, "eqcsfield") // returns true

警告:可以传递结构进行验证,例如。time.Time是一个结构,或者您具有自定义类型并注册了自定义类型处理程序,因此必须允许它;但是,如果尝试验证要传递给“ validate.Struct”的结构,则会发生无法预料的验证

对于传入的错误值,它返回InvalidValidationError,否则返回nil或ValidationErrors作为错误。如果错误不为零,则需要声明错误。err.(validator.ValidationErrors)访问错误数组。 validate Array, Slice and maps fields which may contain more than one error

func (*Validate) VarWithValueCtx

1
2
func (v *Validate) VarWithValueCtx(ctx context.Context, field interface{}, other interface{}
, tag string) (err error)

VarWithValue使用标签样式验证(例如)针对另一个变量/字段的值来验证单个变量。并允许通过context.Context传递上下文验证验证信息。

1
2
3
s1 := "abcd"
s2 := "abcd"
validate.VarWithValue(s1, s2, "eqcsfield") // returns true

警告:可以传递结构进行验证,例如。time.Time是一个结构,或者您具有自定义类型并注册了自定义类型处理程序,因此必须允许它;但是,如果尝试验证要传递给“ validate.Struct”的结构,则会发生无法预料的验证

对于传入的错误值,它返回InvalidValidationError,否则返回nil或ValidationErrors作为错误。如果错误不为零,则需要声明错误。err.(validator.ValidationErrors)访问错误数组。 validate Array, Slice and maps fields which may contain more than one error

type ValidationErrors

1
type ValidationErrors []FieldError

ValidationErrors是FieldError的数组,用于验证后的自定义错误消息。

func (ValidationErrors) Error

1
func (ve ValidationErrors) Error() string

Error 旨在用于开发+调试,而并非旨在作为生产错误消息。它允许ValidationErrors订阅Error接口。在ValidationErrors数组中找到的FieldError中包含创建特定于您的应用程序的错误消息的所有信息。

func (ValidationErrors) Translate

1
func (ve ValidationErrors) Translate(ut ut.Translator) ValidationErrorsTranslations

Translate 会翻译所有ValidationErrors

type ValidationErrorsTranslations

1
type ValidationErrorsTranslations map[string]string

ValidationErrorsTranslations是Translate返回类型

嵌入验证器和标签

这是当前内置验证器的列表:

Skip Field

告诉验证跳过此struct字段;这在忽略嵌入式结构被验证时特别方便。(用法:-)

1
Usage: -

Or Operator

这是允许多个验证器使用和接受的“或”运算符。(用法:rbg | rgba)<-这将允许接受rgb或rgba颜色。例如,也可以将其与’and’结合使用(用法:omitempty,rgb | rgba)

1
Usage: |

StructOnly

当遇到作为嵌套结构的字段并包含此标志时,将对嵌套结构进行任何验证,但不会验证任何嵌套结构字段。如果您在程序内部知道该结构将是有效的,但是需要验证它是否已被分配,则这很有用。注意:在结构本身上只能使用“required”和“ omitempty”。

1
Usage: structonly

NoStructLevel

与structonly标记相同,除了不会运行任何结构级别的验证。

1
Usage: nostructlevel

Omit Empty

允许条件验证,例如,如果未为字段设置值(由“required”验证器确定),则其他验证(例如min或max)将不会运行,但是如果设置了值,验证将运行。

1
Usage: omitempty

Dive

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

这告诉验证者进入slice, array, map ,并使用后面的验证标签验证slice, array, map的级别。还支持多维嵌套,您要Dive的每个级别都将需要另一个Dive标签。潜水有一些子标签,“keys”和“endkeys”,请参阅下面的“ Keys & EndKeys”部分。

1
Usage: dive
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
Example #1

[][]string with validation tag "gt=0,dive,len=1,dive,required"
// gt=0 will be applied to []
// len=1 will be applied to []string
// required will be applied to string
Example #2

[][]string with validation tag "gt=0,dive,dive,required"
// gt=0 will be applied to []
// []string will be spared validation
// required will be applied to string

Keys & EndKeys

它们将在dive标签之后直接一起使用,并告诉验证者“keys”和“endkeys”之间的任何内容都适用于map的keys,而不是values。可以将其视为“ dive”标签,但适用于map keys而不是values。还支持多维嵌套,您要验证的每个级别都将需要另一个“keys”和“endkeys”标签。这些标签仅对map有效。

1
Usage: dive,keys,othertagvalidation(s),endkeys,valuevalidationtags
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
Example #1

map[string]string with validation tag "gt=0,dive,keys,eg=1|eq=2,endkeys,required"
// gt=0 will be applied to the map itself
// eg=1|eq=2 will be applied to the map keys
// required will be applied to map values
Example #2

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

Required

这可以验证该值不是数据类型默认的零值。对于数字,请确保值不为零。对于字符串,请确保值不是“”。对于切片,映射,指针,接口,通道和函数,请确保该值不为nil。

1
Usage: required

Required With

仅当存在任何其他指定的字段时,验证下的字段必须存在且不能为空。对于字符串,请确保值不是“”。对于切片,映射,指针,接口,通道和函数,请确保该值不为零。

1
Usage: required_with

Examples:

1
2
3
4
5
// require the field if the Field1 is present:
Usage: required_with=Field1

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

Required With All

仅当所有其他指定的字段都存在时,验证中的字段必须存在且不为空。对于字符串,请确保值不是“”。对于切片,映射,指针,接口,通道和函数,请确保该值不为nil。

1
Usage: required_with_all

Example:

1
2
// require the field if the Field1 and Field2 is present:
Usage: required_with_all=Field1 Field2

Required Without

仅当不存在任何其他指定字段时,验证下的字段必须存在且不为空。对于字符串,请确保值不是“”。对于切片,映射,指针,接口,通道和函数,请确保该值不为nil.

1
Usage: required_without

Examples:

1
2
3
4
5
// require the field if the Field1 is not present:
Usage: required_without=Field1

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

Required Without All

仅当所有其他指定字段都不存在时,验证中的字段必须存在且不为空。对于字符串,请确保值不是“”。对于切片,映射,指针,接口,通道和函数,请确保该值不为零。

1
Usage: required_without_all

Example:

1
2
// require the field if the Field1 and Field2 is not present:
Usage: required_without_all=Field1 Field2

Is Default

这可以验证该值是默认值,并且几乎与Required相反。

1
Usage: isdefault

Length

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

对于数字,长度将确保该值等于给定的参数。对于字符串,它将检查字符串长度是否恰好等于该字符数。对于切片,数组和map,验证项目数。

1
Usage: len=10

Maximum

对于数字,max将确保该值小于或等于给定的参数。对于字符串,它将检查字符串长度是否最多为该字符数。对于切片,数组和地图,验证项目数。

1
Usage: max=10

Minimum

对于数字,max将确保该值小于或等于给定的参数。对于字符串,它将检查字符串长度是否最多为该字符数。对于切片,数组和地图,验证项目数。

1
Usage: min=10

Equals

对于字符串和数字,eq将确保该值等于给定的参数。对于切片,数组和地图,验证项目数。

1
Usage: eq=10

Not Equal

对于字符串和数字,ne将确保该值不等于给定的参数。对于切片,数组和地图,验证项目数。

1
Usage: ne=10

One Of

对于字符串,整数和整数,oneof将确保该值是参数中的值之一。该参数应该是由空格分隔的值列表。值可以是字符串或数字。

1
2
Usage: oneof=red green
       oneof=5 7 9

Greater Than

对于数字,这将确保该值大于给定的参数。对于字符串,它检查字符串长度是否大于该字符数。对于切片,数组和映射,它会验证项目数。

1
Usage: gt
1
2
3
4
5
6
7
Example #1

Usage: gt=10

Example #2 (time.Time)

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

Greater Than or Equal

Same as ‘min’ above. Kept both to make terminology with ’len’ easier.

1
Usage: gt
1
2
3
4
5
6
7
Example #1

Usage: gte=10

Example #2 (time.Time)

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

Less Than

对于数字,这将确保该值小于给定的参数。对于字符串,它检查字符串长度是否小于该字符数。对于切片,数组和映射,它会验证项目数。

1
Usage: lt
1
2
3
4
Example #1

Usage: lt=10
Example #2 (time.Time) For time.Time ensures the time value is less than time.Now.UTC().

Less Than or Equal

与上面的“最大”相同。两者都保留以使用“ len”表示的术语更容易。

1
2
3
4
5
6
7
8
Example #1

Usage: lte=10
Example #2 (time.Time)

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

Usage: lte

Field Equals Another Field

这将针对结构中或传入字段中的另一个字段值来验证该字段值。

Example #1:

1
2
// Validation on Password field using:
Usage: eqfield=ConfirmPassword

Example #2:

1
2
// Validating by field:
validate.VarWithValue(password, confirmpassword, "eqfield")

Field Equals Another Field (relative)

这与nefield相同,除了它会验证相对于顶层结构提供的字段。

1
Usage: eqcsfield=InnerStructField.Field)

Field Does Not Equal Another Field

这将针对结构中或传入字段中的另一个字段值来验证该字段值。

Examples:

1
2
3
4
5
6
7
// Confirm two colors are not the same:
//
// Validation on Color field:
Usage: nefield=Color2

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

Field Does Not Equal Another Field (relative)

这与nefield相同,除了它会验证相对于顶层结构提供的字段。

1
Usage: necsfield=InnerStructField.Field

Field Greater Than Another Field

仅对Numbers和time.Time类型有效,这将针对结构中或传入字段中的另一个字段值验证该字段值。使用示例用于验证开始日期和结束日期:

1
2
3
4
5
6
7
8
Example #1:

// Validation on End field using:
validate.Struct Usage(gtfield=Start)
Example #2:

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

Field Greater Than Another Relative Field

这与gtfield相同,除了它会验证相对于顶层结构提供的字段。

1
Usage: gtcsfield=InnerStructField.Field

Field Greater Than or Equal To Another Field

仅对Numbers和time.Time类型有效,这将针对结构中或传入字段中的另一个字段值验证该字段值。使用示例用于验证开始日期和结束日期:

1
2
3
4
5
6
7
8
Example #1:

// Validation on End field using:
validate.Struct Usage(gtefield=Start)
Example #2:

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

Field Greater Than or Equal To Another Relative Field

这与gtefield相同,除了它会验证相对于顶层结构提供的字段。

1
Usage: gtecsfield=InnerStructField.Field

Less Than Another Field

仅对Numbers和time.Time类型有效,这将针对结构中或传入字段中的另一个字段值验证该字段值。使用示例用于验证开始日期和结束日期:

1
2
3
4
5
6
7
8
Example #1:

// Validation on End field using:
validate.Struct Usage(ltfield=Start)
Example #2:

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

Less Than Another Relative Field

这与ltfield相同,除了它会验证相对于顶层结构提供的字段。

1
Usage: ltcsfield=InnerStructField.Field

Less Than or Equal To Another Field

仅对Numbers和time.Time类型有效,这将针对结构中或传入字段中的另一个字段值验证该字段值。使用示例用于验证开始日期和结束日期:

1
2
3
4
5
6
7
8
Example #1:

// Validation on End field using:
validate.Struct Usage(ltefield=Start)
Example #2:

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

Less Than or Equal To Another Relative Field

这与ltefield相同,除了它会验证相对于顶层结构提供的字段。

1
Usage: ltecsfield=InnerStructField.Field

Field Contains Another Field

除结构字段外,此功能与contains相同。它只能与字符串类型一起使用。有关其他类型的行为,请参见reflect.Value.String()的行为。

1
Usage: containsfield=InnerStructField.Field

Field Excludes Another Field

除了结构字段外,这与exclude相同。它只能与字符串类型一起使用。有关其他类型的行为,请参见reflect.Value.String()的行为。

1
Usage: excludesfield=InnerStructField.Field

Unique

对于数组和切片,Unique将确保没有重复。对于map,Unique将确保没有重复的值。

1
Usage: unique

Alpha Only

这可以验证字符串值仅包含ASCII字母字符

1
Usage: alpha

Alphanumeric

这可以验证字符串值仅包含ASCII字母数字字符

1
Usage: alphanum

Alpha Unicode

这可以验证字符串值仅包含Unicode字母字符

1
Usage: alphaunicode

Alphanumeric Unicode

这可以验证字符串值仅包含Unicode字母数字字符

1
Usage: alphanumunicode

Numeric

这验证了字符串值包含基本数字值。基本不包括指数等…对于整数或浮点数,它返回true。

1
Usage: numeric

Hexadecimal String

这可以验证字符串值包含有效的十六进制。

1
Usage: hexadecimal

Hexcolor String

这可以验证字符串值包含有效的十六进制颜色(包括井号(#))

1
Usage: hexcolor

RGB String

这可以验证字符串值包含有效的rgb颜色

1
Usage: rgb

RGBA String

这可以验证字符串值包含有效的rgba颜色

1
Usage: rgba

HSL String

这可以验证字符串值包含有效的hsl颜色

1
Usage: hsl

HSLA String

这可以验证字符串值包含有效的hsla颜色

1
Usage: hsla

E-mail String

这可以验证字符串值包含有效的电子邮件。这可能不符合任何RFC标准的所有可能性,但是任何电子邮件提供商都不接受所有可能性。

1
Usage: email

File path

这将验证字符串值包含有效的文件路径以及该文件在计算机上是否存在。这是使用os.Stat完成的,它是一个与平台无关的功能。

1
Usage: file

URL String

这将验证字符串值是否包含有效的网址。该网址将接受uri接受的golang请求的任何网址,但必须包含scheme,例如http://或rtmp://

1
Usage: url

URI String

这将验证字符串值包含有效的uri。它将接受golang请求uri接受的任何uri

1
Usage: uri

Urn RFC 2141 String

这验证了根据RFC 2141规范,字符串值包含有效的URN 。

1
Usage: urn_rfc2141

Base64 String

这将验证字符串值包含有效的base64值。尽管空字符串是有效的base64,但这将报告一个空字符串作为错误,但是,如果您希望接受一个空字符串,则可以将其与omitempty标记一起使用。

1
Usage: base64

Base64URL String

这将验证字符串值是否包含符合RFC4648规范的有效base64 URL安全值。尽管空字符串是有效的base64 URL安全值,但这将报告一个空字符串作为错误,如果您希望接受一个空字符串为有效字符串,则可以将其与omitempty标记一起使用。

1
Usage: base64url

Bitcoin Address

这可以验证字符串值包含有效的比特币地址。检查字符串的格式以确保它与三种格式P2PKH,P2SH之一匹配并执行校验和验证。

1
Usage: btc_addr

比特币Bech32地址(隔离见证)

这可以验证字符串值包含由bip-0173(https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki) 定义的有效比特币Bech32地址。特别感谢Pieter Wuille提供了参考实现。

1
Usage: btc_addr_bech32

Ethereum Address

这可以验证字符串值包含有效的以太坊地址。检查字符串的格式以确保它与标准的以太坊地址格式匹配完全验证被https://github.com/golang/crypto/pull/28阻止

1
Usage: eth_addr

Contains

这验证了字符串值包含子字符串值。

1
Usage: contains=@

Contains Any

这可以验证字符串值在子字符串值中是否包含任何Unicode代码点。

1
Usage: containsany=!@#?

Contains Rune

这将验证字符串值包含提供的Rune值。

1
Usage: containsrune=@

Excludes

这验证了字符串值不包含子字符串值。

1
Usage: excludes=@

Excludes All

这可以验证字符串值在子字符串值中不包含任何Unicode代码点。

1
Usage: excludesall=!@#?

Excludes Rune

这可以验证字符串值不包含提供的Rune值。

1
Usage: excludesrune=@

Starts With

这将验证字符串值以提供的字符串值开头

1
Usage: startswith=hello

Ends With

这可以验证字符串值以提供的字符串值结尾

1
Usage: endswith=goodbye

International Standard Book Number

这将验证字符串值包含有效的isbn10或isbn13值。

1
Usage: isbn

International Standard Book Number 10

这验证了字符串值包含有效的isbn10值。

1
Usage: isbn10

International Standard Book Number 13

这验证了字符串值包含有效的isbn13值。

1
Usage: isbn13

Universally Unique Identifier UUID

这将验证字符串值包含有效的UUID。大写的UUID值不会通过-改用uuid_rfc4122

1
Usage: uuid

Universally Unique Identifier UUID v3

这将验证字符串值包含有效的版本3 UUID。大写的UUID值不会通过-改用uuid3_rfc4122

1
Usage: uuid3

Universally Unique Identifier UUID v4

这将验证字符串值包含有效的版本4 UUID。大写的UUID值不会通过-改用uuid4_rfc4122

1
Usage: uuid4

Universally Unique Identifier UUID v5

这将验证字符串值包含有效的版本5 UUID。大写的UUID值不会通过-改用uuid5_rfc4122

1
Usage: uuid5

ASCII

这可以验证字符串值仅包含ASCII字符。注意:如果字符串为空,则验证为true。

1
Usage: ascii

Printable ASCII

这可以验证字符串值仅包含可打印的ASCII字符。注意:如果字符串为空,则验证为true。

1
Usage: printascii

Multi-Byte Characters

这验证了字符串值包含一个或多个多字节字符。注意:如果字符串为空,则验证为true。

1
Usage: multibyte

Data URL

这将验证字符串值包含有效的DataURI。注意:这还将验证数据部分是有效的base64

1
Usage: datauri

Latitude

这验证了字符串值包含有效的纬度。

1
Usage: latitude

Longitude

这可以验证字符串值包含有效的经度。

1
Usage: longitude

Social Security Number SSN

这将验证字符串值包含有效的美国社会安全号码。

1
Usage: ssn

Internet Protocol Address IP

这可以验证字符串值包含有效的IP地址。

1
Usage: ip

Internet Protocol Address IPv4

这将验证字符串值包含有效的v4 IP地址。

1
Usage: ipv4

Internet Protocol Address IPv6

这将验证字符串值包含有效的v6 IP地址。

1
Usage: ipv6

Classless Inter-Domain Routing CIDR

这将验证字符串值包含有效的CIDR地址。

1
Usage: cidr

Classless Inter-Domain Routing CIDRv4

这将验证字符串值包含有效的v4 CIDR地址。

1
Usage: cidrv4

Classless Inter-Domain Routing CIDRv6

这将验证字符串值包含有效的v6 CIDR地址。

1
Usage: cidrv6

Transmission Control Protocol Address TCP

这可以验证字符串值包含有效的可解析TCP地址。

1
Usage: tcp_addr

Transmission Control Protocol Address TCPv4

这将验证字符串值包含有效的可解析v4 TCP地址。

1
Usage: tcp4_addr

Transmission Control Protocol Address TCPv6

这将验证字符串值包含有效的可解析v6 TCP地址。

1
Usage: tcp6_addr

User Datagram Protocol Address UDP

这将验证字符串值包含有效的可解析UDP地址。

1
Usage: udp_addr

User Datagram Protocol Address UDPv4

这将验证字符串值包含有效的可解析v4 UDP地址。

1
Usage: udp4_addr

User Datagram Protocol Address UDPv6

这将验证字符串值包含有效的可解析v6 UDP地址。

1
Usage: udp6_addr

Internet Protocol Address IP

这可以验证字符串值包含有效的可解析IP地址。

1
Usage: ip_addr

Internet Protocol Address IPv4

这将验证字符串值包含有效的可解析v4 IP地址。

1
Usage: ip4_addr

Internet Protocol Address IPv6

这将验证字符串值包含有效的可解析v6 IP地址。

1
Usage: ip6_addr

Unix domain socket end point Address

这将验证字符串值包含有效的Unix地址。

1
Usage: unix_addr

Media Access Control Address MAC

这可以验证字符串值包含有效的MAC地址。

1
Usage: mac

注意:有关可接受的格式和类型,请参见Go’s ParseMAC:

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

Hostname RFC 952

这将根据RFC 952 https://tools.ietf.org/html/rfc952 验证字符串值是有效的主机名

1
Usage: hostname

Hostname RFC 1123

这会根据RFC 1123 https://tools.ietf.org/html/rfc1123 验证字符串值是有效的主机名

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

Full Qualified Domain Name (FQDN)

这将验证字符串值包含有效的FQDN。

1
Usage: fqdn

HTML Tags

这可以验证字符串值似乎是HTML元素标签,包括https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element中描述的那些

1
Usage: html

HTML Encoded

这可以验证字符串值是十进制或十六进制格式的正确字符引用

1
Usage: html_encoded

URL Encoded

这验证了根据 https://tools.ietf.org/html/rfc3986#section-2.1 对字符串值进行百分比编码(URL编码)

1
Usage: url_encoded

Directory

这将验证字符串值包含有效目录,并且该目录存在于计算机上。这是使用os.Stat完成的,它是一个与平台无关的功能。

1
Usage: dir