Introduction

To avoid confusion caused by default values in structs, starting from version goframe v2.0, we have added an Assoc method. This method allows struct validation to be strictly based on the given parameters rather than on the struct’s property values (to avoid the effect of default struct property values). The validation rules will still be automatically read from the gvalid tag within the struct.

Struct Validation - Assoc - 图1tip

This is particularly useful for scenarios that require validation of client request parameters.

Usage Example

  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. type User struct {
  8. Name string `v:"required#Please enter user name"`
  9. Type int `v:"required#Please select user type"`
  10. }
  11. var (
  12. ctx = gctx.New()
  13. user = User{}
  14. data = g.Map{
  15. "name": "john",
  16. }
  17. )
  18. err := g.Validator().Assoc(data).Data(user).Run(ctx)
  19. if err != nil {
  20. g.Dump(err.Items())
  21. }
  22. }

After execution, the terminal output is:

  1. [
  2. {
  3. "Type": {
  4. "required": "Please select user type"
  5. }
  6. }
  7. ]

As you can see, the validation rule required for the Type attribute in the struct was not affected by the default value and was still executed as expected.