当给定的数据校验规则中不包含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:
//
}
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:
//
}
需要注意的是,如果键值为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:
//
}
执行后,终端输出:
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",
},
}
新闻标题:创新互联GoFrame教程:GoFrame 数据校验-可选校验
URL链接:http://www.csdahua.cn/qtweb/news31/507431.html
网站建设、网络推广公司-快上网,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 快上网