Skip to content
This repository was archived by the owner on Dec 23, 2025. It is now read-only.

Commit 0aa26a6

Browse files
committed
feat(validator): Add default validator
Change-Id: Ic15931951127e119daca629fd5d8223092416587
1 parent 1b48e99 commit 0aa26a6

File tree

3 files changed

+27
-7
lines changed

3 files changed

+27
-7
lines changed

validator/README.md

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,12 +22,10 @@ package validator_test
2222
import (
2323
"fmt"
2424

25-
"github.com/bytedance/go-tagexpr/validator"
25+
vd "github.com/bytedance/go-tagexpr/validator"
2626
)
2727

2828
func Example() {
29-
var vd = validator.New("vd")
30-
3129
type InfoRequest struct {
3230
Name string `vd:"($!='Alice'||(Age)$==18) && regexp('\\w')"`
3331
Age int `vd:"$>0"`
@@ -93,7 +91,7 @@ func Example() {
9391

9492
fmt.Println(vd.Validate(map[string]*F{"a": f}))
9593

96-
fmt.Println(vd.Validate([]*F{f}))
94+
fmt.Println(vd.Validate([][1]*F{{f}}))
9795

9896
f = nil
9997
fmt.Println(vd.Validate(f))

validator/default.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package validator
2+
3+
var defaultValidator = New("vd").SetErrorFactory(defaultErrorFactory)
4+
5+
// Default returns the default validator.
6+
// NOTE:
7+
// The tag name is 'vd'
8+
func Default() *Validator {
9+
return defaultValidator
10+
}
11+
12+
// Validate uses the default validator to validate whether the fields of value is valid.
13+
// NOTE:
14+
// The tag name is 'vd'
15+
func Validate(value interface{}) error {
16+
return defaultValidator.Validate(value)
17+
}
18+
19+
// SetErrorFactory customizes the factory of validation error for the default validator.
20+
// NOTE:
21+
// The tag name is 'vd'
22+
func SetErrorFactory(errFactory func(fieldSelector, msg string) error) {
23+
defaultValidator.SetErrorFactory(errFactory)
24+
}

validator/example_test.go

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,10 @@ package validator_test
33
import (
44
"fmt"
55

6-
"github.com/bytedance/go-tagexpr/validator"
6+
vd "github.com/bytedance/go-tagexpr/validator"
77
)
88

99
func Example() {
10-
var vd = validator.New("vd")
11-
1210
type InfoRequest struct {
1311
Name string `vd:"($!='Alice'||(Age)$==18) && regexp('\\w')"`
1412
Age int `vd:"$>0"`

0 commit comments

Comments
 (0)