gvalid_rule_length.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright 2018 gf Author(https://github.com/gogf/gf). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package gvalid
  7. import (
  8. "github.com/gogf/gf/util/gconv"
  9. "strconv"
  10. "strings"
  11. )
  12. // checkLength checks <value> using length rules.
  13. // The length is calculated using unicode string, which means one chinese character or letter
  14. // both has the length of 1.
  15. func checkLength(value, ruleKey, ruleVal string, customMsgMap map[string]string) string {
  16. var (
  17. msg = ""
  18. runeArray = gconv.Runes(value)
  19. valueLen = len(runeArray)
  20. )
  21. switch ruleKey {
  22. case "length":
  23. var (
  24. min = 0
  25. max = 0
  26. array = strings.Split(ruleVal, ",")
  27. )
  28. if len(array) > 0 {
  29. if v, err := strconv.Atoi(strings.TrimSpace(array[0])); err == nil {
  30. min = v
  31. }
  32. }
  33. if len(array) > 1 {
  34. if v, err := strconv.Atoi(strings.TrimSpace(array[1])); err == nil {
  35. max = v
  36. }
  37. }
  38. if valueLen < min || valueLen > max {
  39. msg = getErrorMessageByRule(ruleKey, customMsgMap)
  40. msg = strings.Replace(msg, ":min", strconv.Itoa(min), -1)
  41. msg = strings.Replace(msg, ":max", strconv.Itoa(max), -1)
  42. return msg
  43. }
  44. case "min-length":
  45. min, err := strconv.Atoi(ruleVal)
  46. if valueLen < min || err != nil {
  47. msg = getErrorMessageByRule(ruleKey, customMsgMap)
  48. msg = strings.Replace(msg, ":min", strconv.Itoa(min), -1)
  49. }
  50. case "max-length":
  51. max, err := strconv.Atoi(ruleVal)
  52. if valueLen > max || err != nil {
  53. msg = getErrorMessageByRule(ruleKey, customMsgMap)
  54. msg = strings.Replace(msg, ":max", strconv.Itoa(max), -1)
  55. }
  56. }
  57. return msg
  58. }