gvalid_custom_rule.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435
  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 "context"
  8. // RuleFunc is the custom function for data validation.
  9. // The parameter `rule` specifies the validation rule string, like "required", "between:1,100", etc.
  10. // The parameter `value` specifies the value for this rule to validate.
  11. // The parameter `message` specifies the custom error message or configured i18n message for this rule.
  12. // The parameter `data` specifies the `data` which is passed to the Validator. It might be type of map/struct or a nil value.
  13. // You can ignore the parameter `data` if you do not really need it in your custom validation rule.
  14. type RuleFunc func(ctx context.Context, rule string, value interface{}, message string, data interface{}) error
  15. var (
  16. // customRuleFuncMap stores the custom rule functions.
  17. // map[Rule]RuleFunc
  18. customRuleFuncMap = make(map[string]RuleFunc)
  19. )
  20. // RegisterRule registers custom validation rule and function for package.
  21. // It returns error if there's already the same rule registered previously.
  22. func RegisterRule(rule string, f RuleFunc) error {
  23. customRuleFuncMap[rule] = f
  24. return nil
  25. }
  26. // DeleteRule deletes custom defined validation rule and its function from global package.
  27. func DeleteRule(rule string) {
  28. delete(customRuleFuncMap, rule)
  29. }