You are viewing an old version of this page. View the current version.
Compare with Current View Page History
« Previous Version 14 Next »
CheckMap
多数据校验即支持同时对多条数据进行校验,需要给定校验规则,并且可以自定义出错时的错误信息。 其中比较重要且复杂的是校验规则参数的定义。
校验方法: https://pkg.go.dev/github.com/gogf/gf/v2/util/gvalid
func CheckMap(ctx context.Context, params interface{}, rules interface{}, messages ...CustomMsg) Error
params
map
rules
[]string
map[string]string
messages
CustomMsg
map[string]interface{}
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()) } }
执行后,终端输出:
{ "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" } }
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类型参数需要指定对应字段、对应规则的错误提示信息,是一个二维的“关联数组”。该示例执行后,终端输出:
messsages
string
{ "passport": { "length": "账号长度应当在6到16之间", "required": "账号不能为空" }, "password": { "same": "两次密码输入不相等" } }