阅读(4993) (12)

GoFrame 数据校验-可选校验

2022-03-30 10:44:01 更新

可选校验规则

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

示例4,通过map传参

package main

import (
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
)

func main() {
	var (
		ctx    = gctx.New()
		params = map[string]interface{}{
			"passport":  "",
			"password":  "123456",
			"password2": "1234567",
		}
		rules = []string{
			"passport@length:6,16",
			"password@required|length:6,16|same:password2",
			"password2@required|length:6,16",
		}
	)
	err := g.Validator().Rules(rules).Data(params).Run(ctx)
	if err != nil {
		g.Dump(err.Maps())
	}
}

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

执行后,终端输出:

{
    "password": {
        "same": "The password value `123456` must be the same as field password2",
    },
}