Relevant Data Structure

Custom rule method definition, and the corresponding input parameter data structure.

  1. // RuleFuncInput holds the input parameters that passed to custom rule function RuleFunc.
  2. type RuleFuncInput struct {
  3. // Rule specifies the validation rule string, like "required", "between:1,100", etc.
  4. Rule string
  5. // Message specifies the custom error message or configured i18n message for this rule.
  6. Message string
  7. // Value specifies the value for this rule to validate.
  8. Value *gvar.Var
  9. // Data specifies the `data` which is passed to the Validator. It might be a type of map/struct or a nil value.
  10. // You can ignore the parameter `Data` if you do not really need it in your custom validation rule.
  11. Data *gvar.Var
  12. }
  13. // RuleFunc is the custom function for data validation.
  14. type RuleFunc func(ctx context.Context, in RuleFuncInput) error

Brief method parameter explanation:

  1. Context parameter ctx is required.
  2. RuleFuncInput data structure explanation:
    • Rule indicates the current validation rule, including rule parameters, such as: required, between:1,100, length:6 etc.
    • Message specifies the validation error message returned upon validation failure.
    • Value specifies the data value being validated. Note that the type is a *gvar.Var generic, so you can pass any type of parameter.
    • Data specifies the parameters passed during validation, useful when validating a map or struct, particularly in joint validation. This value is runtime input and may be nil.

Custom Rule - Registration - 图1tip

Custom errors natively support i18n features. You only need to configure i18n translation information following gf.gvalid.rule.custom_rule_name. This information is automatically fetched from the i18n manager upon validation failure and passed to your registered custom validation method via the Message parameter.

Global Validation Rule Registration

Custom rules are divided into two types: global rule registration and local rule registration.

Global rules are rules that take effect globally. After registration, they can be used for data validation by method or object usage.

Register validation method:

  1. // RegisterRule registers custom validation rule and function for package.
  2. func RegisterRule(rule string, f RuleFunc) {
  3. customRuleFuncMap[rule] = f
  4. }
  5. // RegisterRuleByMap registers custom validation rules using map for package.
  6. func RegisterRuleByMap(m map[string]RuleFunc) {
  7. for k, v := range m {
  8. customRuleFuncMap[k] = v
  9. }
  10. }

You need to define a validation method as per RuleFunc type, implement the validation you need, and then use RegisterRule to register it in the global management of the gvalid module. This registration logic is generally executed during program initialization. This method will be automatically called when data validation is performed; returning nil indicates validation success, otherwise, a non-empty error type value should be returned.

Custom Rule - Registration - 图2warning

Note: The custom rule registration methods do not support concurrent calls. You need to register it during program startup (such as in the boot package); dynamic registration at runtime is not possible, otherwise, it will cause concurrency safety issues.

Example 1, Order ID Existence Validation

In e-commerce business, when we perform operations on orders, we can validate whether the given order ID exists through custom rules. Therefore, we can register a global rule order-exist to achieve this.

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/gogf/gf/v2/database/gdb"
  6. "github.com/gogf/gf/v2/errors/gerror"
  7. "github.com/gogf/gf/v2/frame/g"
  8. "github.com/gogf/gf/v2/os/gctx"
  9. "github.com/gogf/gf/v2/util/gvalid"
  10. "time"
  11. )
  12. type Request struct {
  13. OrderId int64 `v:"required|order-exist"`
  14. ProductName string
  15. Amount int64
  16. // ...
  17. }
  18. func init() {
  19. rule := "order-exist"
  20. gvalid.RegisterRule(rule, RuleOrderExist)
  21. }
  22. func RuleOrderExist(ctx context.Context, in gvalid.RuleFuncInput) error {
  23. // SELECT COUNT(*) FROM `order` WHERE `id` = xxx
  24. count, err := g.Model("order").
  25. Ctx(ctx).
  26. Cache(gdb.CacheOption{
  27. Duration: time.Hour,
  28. Name: "",
  29. Force: false,
  30. }).
  31. WhereNot("id", in.Value.Int64()).
  32. Count()
  33. if err != nil {
  34. return err
  35. }
  36. if count == 0 {
  37. return gerror.Newf(`invalid order id "%d"`, in.Value.Int64())
  38. }
  39. return nil
  40. }
  41. func main() {
  42. var (
  43. ctx = gctx.New()
  44. req = &Request{
  45. OrderId: 65535,
  46. ProductName: "HikingShoe",
  47. Amount: 10000,
  48. }
  49. )
  50. err := g.Validator().CheckStruct(ctx, req)
  51. fmt.Println(err)
  52. }

Example 2, User Uniqueness Rule

During user registration, we often need to check whether the submitted name/account is unique. Therefore, we can register a global rule unique-name to achieve this.

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/gogf/gf/v2/database/gdb"
  6. "github.com/gogf/gf/v2/errors/gerror"
  7. "github.com/gogf/gf/v2/frame/g"
  8. "github.com/gogf/gf/v2/os/gctx"
  9. "github.com/gogf/gf/v2/util/gvalid"
  10. "time"
  11. )
  12. type User struct {
  13. Id int
  14. Name string `v:"required|unique-name#Please enter the user name|User name is already taken"`
  15. Pass string `v:"required|length:6,18"`
  16. }
  17. func init() {
  18. rule := "unique-name"
  19. gvalid.RegisterRule(rule, RuleUniqueName)
  20. }
  21. func RuleUniqueName(ctx context.Context, in gvalid.RuleFuncInput) error {
  22. var user *User
  23. if err := in.Data.Scan(&user); err != nil {
  24. return gerror.Wrap(err, `Scan data to user failed`)
  25. }
  26. // SELECT COUNT(*) FROM `user` WHERE `id` != xxx AND `name` != xxx
  27. count, err := g.Model("user").
  28. Ctx(ctx).
  29. Cache(gdb.CacheOption{
  30. Duration: time.Hour,
  31. Name: "",
  32. Force: false,
  33. }).
  34. WhereNot("id", user.Id).
  35. WhereNot("name", user.Name).
  36. Count()
  37. if err != nil {
  38. return err
  39. }
  40. if count > 0 {
  41. if in.Message != "" {
  42. return gerror.New(in.Message)
  43. }
  44. return gerror.Newf(`user name "%s" is already token by others`, user.Name)
  45. }
  46. return nil
  47. }
  48. func main() {
  49. var (
  50. ctx = gctx.New()
  51. user = &User{
  52. Id: 1,
  53. Name: "john",
  54. Pass: "123456",
  55. }
  56. )
  57. err := g.Validator().CheckStruct(ctx, user)
  58. fmt.Println(err)
  59. }

Local Validation Rule Registration

Local rules are rules that take effect only within the current validation object. Validation rules are registered into the current chain operation process being used rather than globally.

Registration method:

  1. // RuleFunc registers one custom rule function to current Validator.
  2. func (v *Validator) RuleFunc(rule string, f RuleFunc) *Validator
  3. // RuleFuncMap registers multiple custom rule functions to current Validator.
  4. func (v *Validator) RuleFuncMap(m map[string]RuleFunc) *Validator

Brief introduction:

  • RuleFunc method is used to register a single custom validation rule to the current object.
  • RuleFuncMap method is used to register multiple custom validation rules to the current object.

Usage example:

We will change one of the examples above to local validation rule registration.

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/gogf/gf/v2/database/gdb"
  6. "github.com/gogf/gf/v2/errors/gerror"
  7. "github.com/gogf/gf/v2/frame/g"
  8. "github.com/gogf/gf/v2/os/gctx"
  9. "github.com/gogf/gf/v2/util/gvalid"
  10. "time"
  11. )
  12. type Request struct {
  13. OrderId int64
  14. ProductName string
  15. Amount int64
  16. // ...
  17. }
  18. func RuleOrderExist(ctx context.Context, in gvalid.RuleFuncInput) error {
  19. // SELECT COUNT(*) FROM `order` WHERE `id` = xxx
  20. count, err := g.Model("order").
  21. Ctx(ctx).
  22. Cache(gdb.CacheOption{
  23. Duration: time.Hour,
  24. Name: "",
  25. Force: false,
  26. }).
  27. WhereNot("id", in.Value.Int64()).
  28. Count()
  29. if err != nil {
  30. return err
  31. }
  32. if count == 0 {
  33. return gerror.Newf(`invalid order id "%d"`, in.Value.Int64())
  34. }
  35. return nil
  36. }
  37. func main() {
  38. var (
  39. ctx = gctx.New()
  40. req = &Request{
  41. OrderId: 65535,
  42. ProductName: "HikingShoe",
  43. Amount: 10000,
  44. }
  45. )
  46. err := g.Validator().RuleFunc("order-exist", RuleOrderExist).Data(req).Run(ctx)
  47. fmt.Println(err)
  48. }