当给定的数据校验规则中不包含required*
规则时,表示该规则不是一个必须规则,当属性值为nil
或者空字符串
时,将会忽略其校验。
示例1,空字符串
package main
import (
"fmt"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
)
func main() {
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}"`
}
var (
ctx = gctx.New()
obj = &Params{
Page: 1,
Size: 10,
}
)
err := g.Validator().Data(obj).Run(ctx)
fmt.Println(err)
// Output:
// <nil>
}
示例2,空指针属性
package main
import (
"fmt"
"github.com/gogf/gf/v2/container/gvar"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
)
func main() {
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}"`
}
var (
ctx = gctx.New()
obj = &Params{
Page: 1,
Size: 10,
}
)
err := g.Validator().Data(obj).Run(ctx)
fmt.Println(err)
// Output:
// <nil>
}
示例3,空整型属性
需要注意的是,如果键值为0
或者false
,参数值将仍然会被校验。
package main
import (
"fmt"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
)
func main() {
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}"`
}
var (
ctx = gctx.New()
obj = &Params{
Page: 1,
Size: 10,
}
)
err := g.Validator().Data(obj).Run(ctx)
fmt.Println(err)
// Output:
// <nil>
}
执行后,终端输出:
project id must between 1, 10000