File tree Expand file tree Collapse file tree 2 files changed +20
-0
lines changed Expand file tree Collapse file tree 2 files changed +20
-0
lines changed Original file line number Diff line number Diff line change @@ -12,6 +12,11 @@ import (
12
12
// use a single instance of Validate, it caches struct info
13
13
var validate = validator .New ()
14
14
15
+ // SetValidate let validate can use custom rules
16
+ func SetValidate (v * validator.Validate ) {
17
+ validate = v
18
+ }
19
+
15
20
// validatorNeeded checks if the validator is needed to opType
16
21
func validatorNeeded (opType operator.OpType ) bool {
17
22
switch opType {
Original file line number Diff line number Diff line change @@ -2,6 +2,7 @@ package validator
2
2
3
3
import (
4
4
"context"
5
+ "github.com/go-playground/validator/v10"
5
6
"github.com/qiniu/qmgo/operator"
6
7
"github.com/stretchr/testify/require"
7
8
"go.mongodb.org/mongo-driver/bson"
@@ -26,6 +27,11 @@ type Address struct {
26
27
Phone string `validate:"required"`
27
28
}
28
29
30
+ // CustomRule use custom rule
31
+ type CustomRule struct {
32
+ Name string `validate:"required,foo"`
33
+ }
34
+
29
35
func TestValidator (t * testing.T ) {
30
36
ast := require .New (t )
31
37
ctx := context .Background ()
@@ -96,4 +102,13 @@ func TestValidator(t *testing.T) {
96
102
user = nil
97
103
ast .NoError (Do (ctx , user , operator .BeforeInsert ))
98
104
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 ))
99
114
}
You can’t perform that action at this time.
0 commit comments