You are viewing an old version of this page. View the current version.
Compare with Current View Page History
« Previous Version 20 Next »
我们可以将给定的变量当做一个参数进行校验,即单数据校验。
单数据校验必须通过Data方法给定被校验数据,Rule方法给定校验规则。
Data
Rule
单数据校验比较简单,我们来看几个示例。
package main import ( "fmt" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/os/gctx" ) func main() { var ( ctx = gctx.New() rule = "length:6,16" ) if err := g.Validator().Rules(rule).Data("123456").Run(ctx); err != nil { fmt.Println(err.String()) } if err := g.Validator().Rules(rule).Data("12345").Run(ctx); err != nil { fmt.Println(err.String()) } }
执行后,终端输出:
The value `12345` length must be between 6 and 16
package main import ( "fmt" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/os/gctx" ) func main() { var ( ctx = gctx.New() rule = "integer|between:6,16" messages = "请输入一个整数|参数大小不对啊老铁" value = 5.66 ) if err := g.Validator().Rules(rule).Messages(messages).CheckValue(ctx, value); err != nil { fmt.Println(err.Map()) } }
map[between:参数大小不对啊老铁 integer:请输入一个整数]
可以看到,多个规则以及多个自定义错误提示之间使用英文 | 号进行分割,注意自定义错误提示的顺序和多规则的顺序一一对应。messages参数除了支持string类型以外,还支持map[string]string类型,请看以下例子:
|
messages
string
map[string]string
package main import ( "fmt" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/os/gctx" ) func main() { var ( ctx = gctx.New() rule = "url|min-length:11" value = "goframe.org" messages = map[string]string{ "url": "请输入正确的URL地址", "min-length": "地址长度至少为{min}位", } ) if err := g.Validator().Rules(rule).Messages(messages).CheckValue(ctx, value); err != nil { fmt.Println(err.Map()) } }
map[url:请输入正确的URL地址]
package main import ( "fmt" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/os/gctx" ) func main() { var ( ctx = gctx.New() rule = `regex:\d{6,}|\D{6,}|max-length:16` ) if err := g.Validator().Rules(rule).CheckValue(ctx, `123456`); err != nil { fmt.Println(err) } if err := g.Validator().Rules(rule).CheckValue(ctx, `abcde6`); err != nil { fmt.Println(err) } }
The value `abcde6` must be in regex of: \d{6,}|\D{6,}