当给定的数据校验规则中不包含required*
规则时,表示该规则不是一个必须规则。如果当给定的值为nil
或者空字符串时,将会忽略其校验。
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>
}
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>
}
需要注意的是,如果键值为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
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",
},
}
备案信息: 粤ICP备15087711号-2
Copyright © 2008-2024 啊嘎哇在线工具箱 All Rights.
本站所有资料来源于网络,版权归原作者所有,仅作学习交流使用,如不慎侵犯了您的权利,请联系我们。