Skip to content

Commit b67a2c1

Browse files
authored
Merge pull request #232 from liasica/fix-validator-use-custom-rule-FATAL-ERROR-stack-overflow
fix: [#231] fix validator use custom rule FATAL ERROR stack overflow
2 parents 7a07ca4 + 9cc32f5 commit b67a2c1

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

validator/validator.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,11 @@ import (
1212
// use a single instance of Validate, it caches struct info
1313
var validate = validator.New()
1414

15+
// SetValidate let validate can use custom rules
16+
func SetValidate(v *validator.Validate) {
17+
validate = v
18+
}
19+
1520
// validatorNeeded checks if the validator is needed to opType
1621
func validatorNeeded(opType operator.OpType) bool {
1722
switch opType {

validator/validator_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package validator
22

33
import (
44
"context"
5+
"github.com/go-playground/validator/v10"
56
"github.com/qiniu/qmgo/operator"
67
"github.com/stretchr/testify/require"
78
"go.mongodb.org/mongo-driver/bson"
@@ -26,6 +27,11 @@ type Address struct {
2627
Phone string `validate:"required"`
2728
}
2829

30+
// CustomRule use custom rule
31+
type CustomRule struct {
32+
Name string `validate:"required,foo"`
33+
}
34+
2935
func TestValidator(t *testing.T) {
3036
ast := require.New(t)
3137
ctx := context.Background()
@@ -96,4 +102,13 @@ func TestValidator(t *testing.T) {
96102
user = nil
97103
ast.NoError(Do(ctx, user, operator.BeforeInsert))
98104
ast.NoError(Do(ctx, nil, operator.BeforeInsert))
105+
106+
// use custom rules
107+
customRule := &CustomRule{Name: "bar"}
108+
v := validator.New()
109+
_ = v.RegisterValidation("foo", func(fl validator.FieldLevel) bool {
110+
return fl.Field().String() == "bar"
111+
})
112+
SetValidate(v)
113+
ast.NoError(Do(ctx, customRule, operator.BeforeInsert))
99114
}

0 commit comments

Comments
 (0)