当给定的数据校验规则中不包含required*规则时,表示该规则不是一个必须规则,当属性值为nil或者空字符串时,将会忽略其校验。

示例1,空字符串

type Params struct {
	Page      int    `v:"required|min:1         # page is required"`
	Size      int    `v:"required|between:1,100 # size is required"`
	ProjectId string `v:"between:1,10000        # project id must between :min, :max"`
}
obj := &Params{
	Page: 1,
	Size: 10,
}
err := gvalid.CheckStruct(context.TODO(), obj, nil)
fmt.Println(err)
// Output:
// <nil>

示例2,空指针属性

type Params struct {
	Page      int       `v:"required|min:1         # page is required"`
	Size      int       `v:"required|between:1,100 # size is required"`
	ProjectId *gvar.Var `v:"between:1,10000        # project id must between :min, :max"`
}
obj := &Params{
	Page: 1,
	Size: 10,
}
err := gvalid.CheckStruct(context.TODO(), obj, nil)
fmt.Println(err)
// Output:
// <nil>

示例3,空整型属性

需要注意的是,如果键值为0或者false,参数值将仍然会被校验。

type Params struct {
	Page      int `v:"required|min:1         # page is required"`
	Size      int `v:"required|between:1,100 # size is required"`
	ProjectId int `v:"between:1,10000        # project id must between :min, :max"`
}
obj := &Params{
	Page: 1,
	Size: 10,
}
err := gvalid.CheckStruct(context.TODO(), obj, nil)
fmt.Println(err)
// Output:
// project id must between 1, 10000
















Content Menu

  • No labels