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

示例1,空字符串

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gogf/gf/v2/frame/g"
  5. "github.com/gogf/gf/v2/os/gctx"
  6. )
  7. func main() {
  8. type Params struct {
  9. Page int `v:"required|min:1 # page is required"`
  10. Size int `v:"required|between:1,100 # size is required"`
  11. ProjectId string `v:"between:1,10000 # project id must between {min}, {max}"`
  12. }
  13. var (
  14. ctx = gctx.New()
  15. obj = &Params{
  16. Page: 1,
  17. Size: 10,
  18. }
  19. )
  20. err := g.Validator().Data(obj).Run(ctx)
  21. fmt.Println(err)
  22. // Output:
  23. // <nil>
  24. }

示例2,空指针属性

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gogf/gf/v2/container/gvar"
  5. "github.com/gogf/gf/v2/frame/g"
  6. "github.com/gogf/gf/v2/os/gctx"
  7. )
  8. func main() {
  9. type Params struct {
  10. Page int `v:"required|min:1 # page is required"`
  11. Size int `v:"required|between:1,100 # size is required"`
  12. ProjectId *gvar.Var `v:"between:1,10000 # project id must between {min}, {max}"`
  13. }
  14. var (
  15. ctx = gctx.New()
  16. obj = &Params{
  17. Page: 1,
  18. Size: 10,
  19. }
  20. )
  21. err := g.Validator().Data(obj).Run(ctx)
  22. fmt.Println(err)
  23. // Output:
  24. // <nil>
  25. }

示例3,空整型属性

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

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gogf/gf/v2/frame/g"
  5. "github.com/gogf/gf/v2/os/gctx"
  6. )
  7. func main() {
  8. type Params struct {
  9. Page int `v:"required|min:1 # page is required"`
  10. Size int `v:"required|between:1,100 # size is required"`
  11. ProjectId int `v:"between:1,10000 # project id must between {min}, {max}"`
  12. }
  13. var (
  14. ctx = gctx.New()
  15. obj = &Params{
  16. Page: 1,
  17. Size: 10,
  18. }
  19. )
  20. err := g.Validator().Data(obj).Run(ctx)
  21. fmt.Println(err)
  22. // Output:
  23. // <nil>
  24. }

执行后,终端输出:

  1. project id must between 1, 10000