验证用户输入的数据是我们开发中最常见的需求,Goravel 提供三种验证姿势,个个简单好用!
第一种:简单直接式
根据表单内容直接校验:
func (r *PostController) Store(ctx http.Context) {
validator, err := ctx.Request().Validate(map[string]string{
"title": "required|max_len:255",
"body": "required",
})
}
第二种:自由定义式
自定义验证数据:
validator, err := facades.Validation.Make(map[string]any{
"name": "Goravel",
}, map[string]string{
"title": "required|max_len:255",
"body": "required",
})
第三种:优雅文艺式
使用命令 go run . artisan make:request StorePostRequest
创建一个「表单请求类」,并定义规则:
package requests
import (
"github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/contracts/validation"
)
type StorePostRequest struct {
Name string `form:"name" json:"name"`
}
// 验证授权
func (r *StorePostRequest) Authorize(ctx http.Context) error {
return nil
}
// 定义规则
func (r *StorePostRequest) Rules() map[string]string {
return map[string]string{
"title": "required|max_len:255",
"body": "required",
}
}
// 自定义错误信息
func (r *StorePostRequest) Messages() map[string]string {
return map[string]string{}
}
// 自定义字段名
func (r *StorePostRequest) Attributes() map[string]string {
return map[string]string{}
}
// 数据预处理
func (r *StorePostRequest) PrepareForValidation(data validation.Data) {
}
然后校验:
func (r *PostController) Store(ctx http.Context) {
var storePost requests.StorePostRequest
errors, err := ctx.Request().ValidateRequest(&storePost)
}