Versions Compared
compared with
Key
- This line was added.
- This line was removed.
- Formatting was changed.
多数据校验 - CheckMap
多数据校验即支持同时对多条数据进行校验,需要给定校验规则,并且可以自定义出错时的错误信息。 其中比较重要且复杂的是校验规则参数的定义。
校验方法: https://pkg.go.dev/github.com/gogf/gf/v2/util/gvalid
Code Block | ||
---|---|---|
| ||
func CheckMap(ctx context.Context, params interface{}, rules interface{}, messages ...CustomMsg) Error |
- 其中
params
参数支持任意map
数据类型。 rules
参数支持[]string
/map[string]string
数据类型,前面一种类型支持返回校验结果顺序,后一种不支持(因为map
是无序的)。rules
参数中的map[string]string
是一个二维的关联数组/哈希表,第一维键名为参数键名,第二维为带有错误的校验规则名称,键值为错误信息。messages
参数为自定义的错误信息,为非必需参数,类型为CustomMsg
(map[string]interface{}
)具体使用请参考后续示例。
相关文档
codeChildren Display |
---|
|
package main
import (
"context"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/util/gvalid"
)
func main() {
params := map[string]interface{}{
"passport": "",
"password": "123456",
"password2": "1234567",
}
rules := map[string]string{
"passport": "required|length:6,16",
"password": "required|length:6,16|same:password2",
"password2": "required|length:6,16",
}
err := gvalid.CheckMap(context.TODO(), params, rules)
// 也可以使用链式操作
// err := g.Validator().Rules(rules).CheckMap(params)
if err != nil {
g.Dump(err.Maps())
}
}
执行后,终端输出:
Code Block | ||
---|---|---|
| ||
{
"passport": {
"length": "The passport value length must be between 6 and 16",
"required": "The passport field is required"
},
"password": {
"same": "The password value must be the same as field password2"
}
} |
自定义错误提示
Code Block | ||
---|---|---|
| ||
package main
import (
"context"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/util/gvalid"
)
func main() {
params := map[string]interface{}{
"passport": "",
"password": "123456",
"password2": "1234567",
}
rules := map[string]string{
"passport": "required|length:6,16",
"password": "required|length:6,16|same:password2",
"password2": "required|length:6,16",
}
messages := map[string]interface{}{
"passport": "账号不能为空|账号长度应当在:min到:max之间",
"password": map[string]string{
"required": "密码不能为空",
"same": "两次密码输入不相等",
},
}
err := gvalid.CheckMap(context.TODO(), params, rules, messages)
// 也可以使用链式操作
// err := g.Validator().Messages(messages).Rules(rules).CheckMap(params)
if err != nil {
g.Dump(err.Maps())
}
} |
该示例同时也展示了messsages
自定义错误信息传递的两种数据类型,string
或者map[string]string
。其中map[string]string
类型参数需要指定对应字段、对应规则的错误提示信息,是一个二维的“关联数组”。该示例执行后,终端输出:
language | js |
---|
|
Panel | ||
---|---|---|
| ||
|