默认错误提示

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/os/gctx"
  5. )
  6. func main() {
  7. var (
  8. ctx = gctx.New()
  9. params = map[string]interface{}{
  10. "passport": "",
  11. "password": "123456",
  12. "password2": "1234567",
  13. }
  14. rules = map[string]string{
  15. "passport": "required|length:6,16",
  16. "password": "required|length:6,16|same:password2",
  17. "password2": "required|length:6,16",
  18. }
  19. )
  20. err := g.Validator().Rules(rules).Data(params).Run(ctx)
  21. if err != nil {
  22. g.Dump(err.Maps())
  23. }
  24. }

执行后,终端输出:

  1. {
  2. "passport": {
  3. "required": "The passport field is required",
  4. "length": "The passport value `` length must be between 6 and 16",
  5. },
  6. "password": {
  7. "same": "The password value `123456` must be the same as field password2",
  8. },
  9. }

自定义错误提示

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/os/gctx"
  5. )
  6. func main() {
  7. var (
  8. ctx = gctx.New()
  9. params = map[string]interface{}{
  10. "passport": "",
  11. "password": "123456",
  12. "password2": "1234567",
  13. }
  14. rules = map[string]string{
  15. "passport": "required|length:6,16",
  16. "password": "required|length:6,16|same:password2",
  17. "password2": "required|length:6,16",
  18. }
  19. messages = map[string]interface{}{
  20. "passport": "账号不能为空|账号长度应当在{min}到{max}之间",
  21. "password": map[string]string{
  22. "required": "密码不能为空",
  23. "same": "两次密码输入不相等",
  24. },
  25. }
  26. )
  27. err := g.Validator().Messages(messages).Rules(rules).Data(params).Run(ctx)
  28. if err != nil {
  29. g.Dump(err.Maps())
  30. }
  31. }

该示例同时也展示了messsages自定义错误信息传递的两种数据类型,string或者map[string]string。其中map[string]string类型参数需要指定对应字段、对应规则的错误提示信息,是一个二维的“关联数组”。该示例执行后,终端输出:

  1. {
  2. "passport": {
  3. "length": "账号长度应当在6到16之间",
  4. "required": "账号不能为空"
  5. },
  6. "password": {
  7. "same": "两次密码输入不相等"
  8. }
  9. }