可选校验规则

当给定的数据校验规则中不包含 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

示例4,通过 map 传参

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/os/gctx"
  5. )
  6. func main() {
  7. var (
  8. ctx = gctx.New()
  9. params = map[string]interface{}{
  10. "passport": "",
  11. "password": "123456",
  12. "password2": "1234567",
  13. }
  14. rules = []string{
  15. "passport@length:6,16",
  16. "password@required|length:6,16|same:password2",
  17. "password2@required|length:6,16",
  18. }
  19. )
  20. err := g.Validator().Rules(rules).Data(params).Run(ctx)
  21. if err != nil {
  22. g.Dump(err.Maps())
  23. }
  24. }

需要注意,其中的 passport 键名并没有 required 规则,因此即便给定的 passport 参数为空字符串,不满足规则时,也并没有报错,因为校验组件将其看做可选校验规则。

执行后,终端输出:

  1. {
  2. "password": {
  3. "same": "The password value `123456` must be the same as field password2",
  4. },
  5. }