验证用户输入的数据是我们开发中最常见的需求,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) }
Goravel 是一个功能完备、具有良好扩展能力的 Web 应用程序框架。作为一个起始脚手架帮助 Golang 开发者快速构建自己的应用。
框架风格与 Laravel 保持一致,让 PHPer 不用学习新的框架,也可以愉快的玩转 Golang !致敬 Laravel !
Welcome star, PR and issues !
![]() | 1 king888 2022-12-28 09:29:29 +08:00 随便用 gookit/validate 封装加下泛型,比上面好用多了,还不局限任何框架: https://go.dev/play/p/K65rxl2WXj7 |
![]() | 2 Valid 2022-12-28 18:15:15 +08:00 那我为什么不直接用 laravel |