Default Error Messages

  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. }

After execution, the terminal outputs:

  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. }

Custom Error Messages

  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. }

This example also demonstrates two data types for passing custom error messages through messages, either string or map[string]string. For map[string]string, you need to specify corresponding error messages for each field and rule, forming a two-dimensional associative array. After executing this example, the terminal outputs:

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