Skip to content

Commit

Permalink
Merge pull request #232 from liasica/fix-validator-use-custom-rule-FA…
Browse files Browse the repository at this point in the history
…TAL-ERROR-stack-overflow

fix: [#231] fix validator use custom rule FATAL ERROR stack overflow
  • Loading branch information
jiangz222 authored Apr 3, 2022
2 parents 7a07ca4 + 9cc32f5 commit b67a2c1
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
5 changes: 5 additions & 0 deletions validator/validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ import (
// use a single instance of Validate, it caches struct info
var validate = validator.New()

// SetValidate let validate can use custom rules
func SetValidate(v *validator.Validate) {
validate = v
}

// validatorNeeded checks if the validator is needed to opType
func validatorNeeded(opType operator.OpType) bool {
switch opType {
Expand Down
15 changes: 15 additions & 0 deletions validator/validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package validator

import (
"context"
"github.com/go-playground/validator/v10"
"github.com/qiniu/qmgo/operator"
"github.com/stretchr/testify/require"
"go.mongodb.org/mongo-driver/bson"
Expand All @@ -26,6 +27,11 @@ type Address struct {
Phone string `validate:"required"`
}

// CustomRule use custom rule
type CustomRule struct {
Name string `validate:"required,foo"`
}

func TestValidator(t *testing.T) {
ast := require.New(t)
ctx := context.Background()
Expand Down Expand Up @@ -96,4 +102,13 @@ func TestValidator(t *testing.T) {
user = nil
ast.NoError(Do(ctx, user, operator.BeforeInsert))
ast.NoError(Do(ctx, nil, operator.BeforeInsert))

// use custom rules
customRule := &CustomRule{Name: "bar"}
v := validator.New()
_ = v.RegisterValidation("foo", func(fl validator.FieldLevel) bool {
return fl.Field().String() == "bar"
})
SetValidate(v)
ast.NoError(Do(ctx, customRule, operator.BeforeInsert))
}

0 comments on commit b67a2c1

Please sign in to comment.