Data Validation - Methods - 图1tip

The following list of common methods in the document may be delayed compared to new features in the code. For more methods and examples, please refer to the code documentation: https://pkg.go.dev/github.com/gogf/gf/v2/util/gvalid

New

  • Description: New creates and returns a new object of Validator.

  • Format:

  1. New() *Validator
  • Example:
  1. func ExampleNew() {
  2. validator := gvalid.New()
  3. if err := validator.Data(16).Rules("min:18").Run(context.Background()); err != nil {
  4. fmt.Print(err)
  5. }
  6. // Output:
  7. // The value `16` must be equal or greater than 18
  8. }

Run

  • Description: Run performs validation operations on data with given rules and information.

  • Format:

  1. Run(ctx context.Context) Error
  • Example:
  1. func ExampleValidator_Run() {
  2. // check value mode
  3. if err := g.Validator().Data(16).Rules("min:18").Run(context.Background()); err != nil {
  4. fmt.Println("check value err:", err)
  5. }
  6. // check map mode
  7. data := map[string]interface{}{
  8. "passport": "",
  9. "password": "123456",
  10. "password2": "1234567",
  11. }
  12. rules := map[string]string{
  13. "passport": "required|length:6,16",
  14. "password": "required|length:6,16|same:password2",
  15. "password2": "required|length:6,16",
  16. }
  17. if err := g.Validator().Data(data).Rules(rules).Run(context.Background()); err != nil {
  18. fmt.Println("check map err:", err)
  19. }
  20. // check struct mode
  21. type Params struct {
  22. Page int `v:"required|min:1"`
  23. Size int `v:"required|between:1,100"`
  24. ProjectId string `v:"between:1,10000"`
  25. }
  26. rules = map[string]string{
  27. "Page": "required|min:1",
  28. "Size": "required|between:1,100",
  29. "ProjectId": "between:1,10000",
  30. }
  31. obj := &Params{
  32. Page: 0,
  33. Size: 101,
  34. }
  35. if err := g.Validator().Data(obj).Run(context.Background()); err != nil {
  36. fmt.Println("check struct err:", err)
  37. }
  38. // May Output:
  39. // check value err: The value `16` must be equal or greater than 18
  40. // check map err: The passport field is required; The passport value `` length must be between 6 and 16; The password value `123456` must be the same as field password2
  41. // check struct err: The Page value `0` must be equal or greater than 1; The Size value `101` must be between 1 and 100
  42. }

Clone

  • Description: Clone creates and returns a value copy object of the current Validator.

  • Format:

  1. (v *Validator) Clone() *Validator
  • Example:
  1. func ExampleValidator_Clone() {
  2. if err := g.Validator().Data(16).Rules("min:18").Run(context.Background()); err != nil {
  3. fmt.Println(err)
  4. }
  5. if err := g.Validator().Clone().Data(20).Run(context.Background()); err != nil {
  6. fmt.Println(err)
  7. } else {
  8. fmt.Println("Check Success!")
  9. }
  10. // Output:
  11. // The value `16` must be equal or greater than 18
  12. // Check Success!
  13. }

I18n

  • Description: The I18n method is used to set the I18N internationalization component for the current validation object. By default, the validation component uses the framework’s global default i18n component object.

  • Format:

  1. I18n(i18nManager *gi18n.Manager) *Validator
  • Example:
  1. func ExampleValidator_I18n() {
  2. var (
  3. i18nManager = gi18n.New()
  4. ctxCn = gi18n.WithLanguage(context.Background(), "cn")
  5. validator = gvalid.New()
  6. )
  7. validator = validator.Data(16).Rules("min:18")
  8. if err := validator.Run(context.Background()); err != nil {
  9. fmt.Println(err)
  10. }
  11. if err := validator.I18n(i18nManager).Run(ctxCn); err != nil {
  12. fmt.Println(err)
  13. }
  14. // Output:
  15. // The value `16` must be equal or greater than 18
  16. // 字段值`16`字段最小值应当为18
  17. }

Bail

  • Description: The Bail method is used to set that if any rule fails in subsequent validations, it stops validation immediately and returns the error result.

  • Format:

  1. Bail() *Validator
  • Example:
  1. func ExampleValidator_Bail() {
  2. type BizReq struct {
  3. Account string `v:"required|length:6,16|same:QQ"`
  4. QQ string
  5. Password string `v:"required|same:Password2"`
  6. Password2 string `v:"required"`
  7. }
  8. var (
  9. ctx = context.Background()
  10. req = BizReq{
  11. Account: "gf",
  12. QQ: "123456",
  13. Password: "goframe.org",
  14. Password2: "goframe.org",
  15. }
  16. )
  17. if err := g.Validator().Bail().Data(req).Run(ctx); err != nil {
  18. fmt.Println("Use Bail Error:", err)
  19. }
  20. if err := g.Validator().Data(req).Run(ctx); err != nil {
  21. fmt.Println("Not Use Bail Error:", err)
  22. }
  23. // output:
  24. // Use Bail Error: The Account value `gf` length must be between 6 and 16
  25. // Not Use Bail Error: The Account value `gf` length must be between 6 and 16; The Account value `gf` must be the same as field QQ
  26. }

Ci

  • Description: The Ci method is used to set case-insensitive comparison when requiring value comparison in rules.

  • Format:

  1. Ci() *Validator
  • Example:
  1. func ExampleValidator_Ci() {
  2. type BizReq struct {
  3. Account string `v:"required"`
  4. Password string `v:"required|same:Password2"`
  5. Password2 string `v:"required"`
  6. }
  7. var (
  8. ctx = context.Background()
  9. req = BizReq{
  10. Account: "gf",
  11. Password: "Goframe.org", // Diff from Password2, but because of "ci", rule check passed
  12. Password2: "goframe.org",
  13. }
  14. )
  15. if err := g.Validator().Data(req).Run(ctx); err != nil {
  16. fmt.Println("Not Use CI Error:", err)
  17. }
  18. if err := g.Validator().Ci().Data(req).Run(ctx); err == nil {
  19. fmt.Println("Use CI Passed!")
  20. }
  21. // output:
  22. // Not Use CI Error: The Password value `Goframe.org` must be the same as field Password2
  23. // Use CI Passed!
  24. }

Data

  • Description: The Data method is used to provide data that needs to be jointly validated.

  • Format:

  1. Data(data interface{}) *Validator
  • Example:
  1. func ExampleValidator_Data() {
  2. type BizReq struct {
  3. Password1 string `v:"password"`
  4. Password2 string `v:"password"`
  5. }
  6. var (
  7. ctx = context.Background()
  8. req = BizReq{
  9. Password1: "goframe",
  10. Password2: "gofra", // error length between 6 and 18
  11. }
  12. )
  13. if err := g.Validator().Data(req).Run(ctx); err != nil {
  14. fmt.Print(err)
  15. }
  16. // Output:
  17. // The Password2 value `gofra` is not a valid password format
  18. }

Assoc

  • Description: Assoc is a chain operation function that sets validation data for the current Validator. The parameter assoc is usually of type map, specifying the value of union validator in the map.

  • Note: Using a non-nil assoc parameter will set the useDataInsteadOfObjectAttributes attribute to true.

  • Format:

  1. Assoc(assoc interface{}) *Validator
  • Example:
  1. func ExampleValidator_Assoc() {
  2. type User struct {
  3. Name string `v:"required"`
  4. Type int `v:"required"`
  5. }
  6. data := g.Map{
  7. "name": "john",
  8. }
  9. user := User{}
  10. if err := gconv.Scan(data, &user); err != nil {
  11. panic(err)
  12. }
  13. if err := g.Validator().Data(user).Assoc(data).Run(context.Background()); err != nil {
  14. fmt.Print(err)
  15. }
  16. // Output:
  17. // The Type field is required
  18. }

Rules

  • Description: The Rules method is used to provide custom validation rules for the current chain operation validation.

  • Format:

  1. Rules(rules interface{}) *Validator
  • Example:
  1. func ExampleValidator_Rules() {
  2. if err := g.Validator().Data(16).Rules("min:18").Run(context.Background()); err != nil {
  3. fmt.Println(err)
  4. }
  5. // Output:
  6. // The value `16` must be equal or greater than 18
  7. }

Message

  • Description: The Messages method is used to provide custom error messages for the current chain operation validation.

  • Format:

  1. Messages(messages interface{}) *Validator
  • Example:
  1. func ExampleValidator_Messages() {
  2. if err := g.Validator().Data(16).Rules("min:18").Messages("Can not regist, Age is less then 18!").Run(context.Background()); err != nil {
  3. fmt.Println(err)
  4. }
  5. // Output:
  6. // Can not regist, Age is less then 18!
  7. }

RuleFunc

  • Description: RuleFunc registers a custom validation rule function to the current Validator.

  • Format:

  1. RuleFunc(rule string, f RuleFunc) *Validator
  • Example:
  1. func ExampleValidator_RuleFunc() {
  2. var (
  3. ctx = context.Background()
  4. lenErrRuleName = "LenErr"
  5. passErrRuleName = "PassErr"
  6. lenErrRuleFunc = func(ctx context.Context, in gvalid.RuleFuncInput) error {
  7. pass := in.Value.String()
  8. if len(pass) != 6 {
  9. return errors.New(in.Message)
  10. }
  11. return nil
  12. }
  13. passErrRuleFunc = func(ctx context.Context, in gvalid.RuleFuncInput) error {
  14. pass := in.Value.String()
  15. if m := in.Data.Map(); m["data"] != pass {
  16. return errors.New(in.Message)
  17. }
  18. return nil
  19. }
  20. )
  21. type LenErrStruct struct {
  22. Value string `v:"uid@LenErr#Value Length Error!"`
  23. Data string `p:"data"`
  24. }
  25. st := &LenErrStruct{
  26. Value: "123",
  27. Data: "123456",
  28. }
  29. // single error sample
  30. if err := g.Validator().RuleFunc(lenErrRuleName, lenErrRuleFunc).Data(st).Run(ctx); err != nil {
  31. fmt.Println(err)
  32. }
  33. type MultiErrorStruct struct {
  34. Value string `v:"uid@LenErr|PassErr#Value Length Error!|Pass is not Same!"`
  35. Data string `p:"data"`
  36. }
  37. multi := &MultiErrorStruct{
  38. Value: "123",
  39. Data: "123456",
  40. }
  41. // multi error sample
  42. if err := g.Validator().RuleFunc(lenErrRuleName, lenErrRuleFunc).RuleFunc(passErrRuleName, passErrRuleFunc).Data(multi).Run(ctx); err != nil {
  43. fmt.Println(err)
  44. }
  45. // Output:
  46. // Value Length Error!
  47. // Value Length Error!; Pass is not Same!
  48. }

RuleFuncMap

  • Description: RuleFuncMap registers multiple custom validation rule functions to the current Validator.

  • Format:

  1. RuleFuncMap(m map[string]RuleFunc) *Validator
  • Example:
  1. func ExampleValidator_RuleFuncMap() {
  2. var (
  3. ctx = context.Background()
  4. lenErrRuleName = "LenErr"
  5. passErrRuleName = "PassErr"
  6. lenErrRuleFunc = func(ctx context.Context, in gvalid.RuleFuncInput) error {
  7. pass := in.Value.String()
  8. if len(pass) != 6 {
  9. return errors.New(in.Message)
  10. }
  11. return nil
  12. }
  13. passErrRuleFunc = func(ctx context.Context, in gvalid.RuleFuncInput) error {
  14. pass := in.Value.String()
  15. if m := in.Data.Map(); m["data"] != pass {
  16. return errors.New(in.Message)
  17. }
  18. return nil
  19. }
  20. ruleMap = map[string]gvalid.RuleFunc{
  21. lenErrRuleName: lenErrRuleFunc,
  22. passErrRuleName: passErrRuleFunc,
  23. }
  24. )
  25. type MultiErrorStruct struct {
  26. Value string `v:"uid@LenErr|PassErr#Value Length Error!|Pass is not Same!"`
  27. Data string `p:"data"`
  28. }
  29. multi := &MultiErrorStruct{
  30. Value: "123",
  31. Data: "123456",
  32. }
  33. if err := g.Validator().RuleFuncMap(ruleMap).Data(multi).Run(ctx); err != nil {
  34. fmt.Println(err)
  35. }
  36. // Output:
  37. // Value Length Error!; Pass is not Same!
  38. }