Skip to main content

数据校验

在使用中,经常需要验证前端提交过来的数据是否符合规则,比如非空、长度限制、是否为数字等一系列验证。在GoFrame中,基本上都不用手动写验证规则,框架里已经提供了很多内置的验证规则可以用来验证数据。验证规则详细内容见官方文档数据校验/校验规则

单个规则/错误提示信息

func (c *Controller) Valid(ctx context.Context, rq *api.ValidReq) (rs *api.ValidRes, err error) {
type Data struct {
Name g.Map `v:"required#name不能为空"`
Age int `v:"required"`
Phone string `v:"required"`
}

data := Data{}
err = g.Validator().Bail().Data(data).Run(ctx)

rs = &api.ValidRes{Data: data}
return
}

多个规则

func (c *Controller) Valid(ctx context.Context, rq *api.ValidReq) (rs *api.ValidRes, err error) {
type Data struct {
Name string
Age string `v:"required|integer|min:1#age不能为空|age必须为整数|age不能小于1"`
Phone string
}

data := Data{Age: "1.1"}
err = g.Validator().Bail().Data(data).Run(ctx)

rs = &api.ValidRes{Data: data}
return
}

使用Map指定校验规则

func (c *Controller) Valid(ctx context.Context, rq *api.ValidReq) (rs *api.ValidRes, err error) {
type Data struct {
Name string
Age int
Phone string
}

rules := map[string]string{
"Name": "required|length:6,16",
"Age": "between:18,30",
"Phone": "phone",
}
message := map[string]interface{}{
"Name": map[string]string{
"required": "Name不能为空",
"length": "长度只能为{min}到{max}个字符",
},
"Age": "年龄只能为18到30岁",
}
data := Data{Phone: "123"}
err = g.Validator().Rules(rules).Messages(message).Data(data).Run(ctx)

rs = &api.ValidRes{Data: data}
return
}

规范路由API数据校验

如果输入数据直接在API里定义了结构,可直接将校验规则写上,在请求时会自动校验,不需要再手动调用校验函数。

api/hello.go

type ValidReq struct {
g.Meta `path:"/valid" method:"all"`

Name string `v:"required|length:6,16"`
Age int `v:"required"`
Phone string `v:"phone"`
}

type ValidRes struct {
Data interface{} `json:"data"`
}

controller/hello.go

func (c *Controller) Valid(ctx context.Context, rq *api.ValidReq) (rs *api.ValidRes, err error) {
return
}