validator应该是Golang里进行表单校验的事实标准了,比如在Web框架GIN中,就是默认使用它。表单校验的作用,就是对输入的数据 进行合法判断,如果是不合法的,那么就输出错误。比如:

package main

import (
        "log"

        "github.com/go-playground/validator/v10"
)

type MyStruct struct {
        FirstName string `json:"firstname" validate:"required"`
}

func main() {
        v := validator.New()

        s := MyStruct{"blabla"}
        err := v.Struct(s)
        log.Printf("%+v", err)

        s2 := MyStruct{}
        err = v.Struct(s2)
        log.Printf("%+v", err)
}

执行结果为:

$ go run main.go
2020/04/10 21:28:41 <nil>
2020/04/10 21:28:41 Key: 'MyStruct.FirstName' Error:Field validation for 'FirstName' failed on the 'required' tag
v.Struct
func (v *Validate) Struct(s interface{}) errorfunc (v *Validate) StructExcept(s interface{}, fields ...string) errorfunc (v *Validate) StructFiltered(s interface{}, fn FilterFunc) errorfunc (v *Validate) StructPartial(s interface{}, fields ...string) errorfunc (v *Validate) Var(field interface{}, tag string) errorvalidate.Var(i, "gt=1,lt=10")func (v *Validate) VarWithValue(field interface{}, other interface{}, tag string) errorvalidate.VarWithValue(s1, s2, "eqcsfield")
Ctx
struct tag
type MyStruct struct {
    Email string `validate:"email"`
}
,ANDOR|
package main

import (
        "log"

        "github.com/go-playground/validator/v10"
)

type MyStruct struct {
        Age int `json:"age" validate:"lt=10|gt=20"`
}

func main() {
        v := validator.New()

        s := MyStruct{15}
        err := v.Struct(s)
        log.Printf("%+v", err)

        s2 := MyStruct{9}
        err = v.Struct(s2)
        log.Printf("%+v", err)
}

接着我们来看看常见的校验写法:

emailurljsonfilebase64containsany=!@#?contains=@containsrune=@excludes=@excludesall=!@#?excludesrune=@startswith=helloendswith=goodbyelatitudelongitudeipipv4ipv6datetime=2006-01-02uuiduuid3uuid4uuid5lowercaseuppercasegtlteqgtelteoneof='red green' 'blue yellow'oneof=5 7 9minmaxrequired-

这就是常见的标签的用法和意思,快用起来吧!