Skip to main content

Data Validation

In practice, it's often necessary to validate data submitted from the frontend to ensure it meets certain rules, such as non-empty, length limits, numeric values, and so on. In GoFrame, you typically don't need to manually write validation rules because the framework provides many built-in validation rules that can be used to validate data. For detailed validation rule content, see the official documentation Data Validation/Validation Rules.

Single Rule/Error Message

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

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

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

Multiple Rules

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 cannot be empty|age must be an integer|age must not be less than 1"`
Phone string
}

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

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

Using Map to Specify Validation Rules

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 cannot be empty",
"length": "Length must be between {min} and {max} characters",
},
"Age": "Age must be between 18 and 30 years old",
}
data := Data{Phone: "123"}
err = g.Validator().Rules(rules).Messages(message).Data(data).Run(ctx)

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

Standardize Route API Data Validation

If the input data is directly defined in the API structure, you can directly write the validation rules. The validation will be automatically performed during the request, eliminating the need to manually call the validation function.

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
}