From 9cc32f571b582da8317e2968eb116b514edaf965 Mon Sep 17 00:00:00 2001 From: liasica Date: Mon, 28 Mar 2022 15:07:36 +0800 Subject: [PATCH] fix: [#231] fix validator use custom rule FATAL ERROR stack overflow --- validator/validator.go | 5 +++++ validator/validator_test.go | 15 +++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/validator/validator.go b/validator/validator.go index a09a56d..a624080 100644 --- a/validator/validator.go +++ b/validator/validator.go @@ -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 { diff --git a/validator/validator_test.go b/validator/validator_test.go index 87bf508..9d36e83 100644 --- a/validator/validator_test.go +++ b/validator/validator_test.go @@ -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" @@ -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() @@ -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)) }