以下常用方法列表,文档更新可能滞后于代码新特性,更多的方法及示例请参考代码文档:https://pkg.go.dev/github.com/gogf/gf/v2/util/gvalid

New

  • 说明:New创建并返回一个Validator的新对象。

  • 格式:

    1. New() *Validator
  • 示例:

    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

  • 说明:Run对给定规则和信息的数据进行校验操作。

  • 格式:

    1. Run(ctx context.Context) Error
  • 示例:

    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

  • 说明:Clone创建并返回一个当前Validator的值拷贝对象。

  • 格式:

    1. (v *Validator) Clone() *Validator
  • 示例:

    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

  • 说明:I18n方法用于设置当前校验对象的I18N国际化组件。默认情况下,校验组件使用的是框架全局默认的i18n组件对象。

  • 格式:

    1. I18n(i18nManager *gi18n.Manager) *Validator
  • 示例:

    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

  • 说明:Bail方法用于设定只要后续的多个校验中有一个规则校验失败则停止校验立即返回错误结果。

  • 格式:

    1. Bail() *Validator
  • 示例:

    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

  • 说明:Ci方法用于设置需要比较数值的规则时,不区分字段的大小写。

  • 格式:

    1. Ci() *Validator
  • 示例:

    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

  • 说明:Data方法用于传递需要联合校验的数据。

  • 格式:

    1. Data(data interface{}) *Validator
  • 示例:

    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

  • 说明:Assoc是一个链式操作函数,为当前Validator设置验证的数据。参数assoc的类型通常是map,指定了union validator中的map的值。

  • 注意:使用非nilassoc参数,会将useDataInsteadOfObjectAttributes属性设置为true

  • 格式:

    1. Assoc(assoc interface{}) *Validator
  • 示例:

    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

  • 说明:Rules方法用于传递当前链式操作校验的自定义校验规则。

  • 格式:

    1. Rules(rules interface{}) *Validator
  • 示例:

    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

  • 说明:Messages方法用于传递当前链式操作校验的自定义错误提示信息。

  • 格式:

    1. Messages(messages interface{}) *Validator
  • 示例:

    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

  • 说明:RuleFunc向当前的Validator注册一个自定义校验规则的函数。

  • 格式:

    1. RuleFunc(rule string, f RuleFunc) *Validator
  • 示例:

    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

  • 说明:RuleFuncMap向当前的Validator注册多个自定义校验规则的函数。

  • 格式:

    1. RuleFuncMap(m map[string]RuleFunc) *Validator
  • 示例:

    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. }