gvalid_register.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright GoFrame Author(https://goframe.org). 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. "context"
  9. "fmt"
  10. "reflect"
  11. "runtime"
  12. "github.com/gogf/gf/v2/container/gvar"
  13. "github.com/gogf/gf/v2/internal/intlog"
  14. )
  15. // RuleFunc is the custom function for data validation.
  16. type RuleFunc func(ctx context.Context, in RuleFuncInput) error
  17. // RuleFuncInput holds the input parameters that passed to custom rule function RuleFunc.
  18. type RuleFuncInput struct {
  19. // Rule specifies the validation rule string, like "required", "between:1,100", etc.
  20. Rule string
  21. // Message specifies the custom error message or configured i18n message for this rule.
  22. Message string
  23. // Value specifies the value for this rule to validate.
  24. Value *gvar.Var
  25. // Data specifies the `data` which is passed to the Validator. It might be a type of map/struct or a nil value.
  26. // You can ignore the parameter `Data` if you do not really need it in your custom validation rule.
  27. Data *gvar.Var
  28. }
  29. var (
  30. // customRuleFuncMap stores the custom rule functions.
  31. // map[Rule]RuleFunc
  32. customRuleFuncMap = make(map[string]RuleFunc)
  33. )
  34. // RegisterRule registers custom validation rule and function for package.
  35. func RegisterRule(rule string, f RuleFunc) {
  36. if customRuleFuncMap[rule] != nil {
  37. intlog.PrintFunc(context.TODO(), func() string {
  38. return fmt.Sprintf(
  39. `rule "%s" is overwrotten by function "%s"`,
  40. rule, runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name(),
  41. )
  42. })
  43. }
  44. customRuleFuncMap[rule] = f
  45. }
  46. // RegisterRuleByMap registers custom validation rules using map for package.
  47. func RegisterRuleByMap(m map[string]RuleFunc) {
  48. for k, v := range m {
  49. customRuleFuncMap[k] = v
  50. }
  51. }
  52. // GetRegisteredRuleMap returns all the custom registered rules and associated functions.
  53. func GetRegisteredRuleMap() map[string]RuleFunc {
  54. if len(customRuleFuncMap) == 0 {
  55. return nil
  56. }
  57. ruleMap := make(map[string]RuleFunc)
  58. for k, v := range customRuleFuncMap {
  59. ruleMap[k] = v
  60. }
  61. return ruleMap
  62. }
  63. // DeleteRule deletes custom defined validation one or more rules and associated functions from global package.
  64. func DeleteRule(rules ...string) {
  65. for _, rule := range rules {
  66. delete(customRuleFuncMap, rule)
  67. }
  68. }