feat(valid)!: promote to v1.0.0 — JSON tag name resolution, bump xerrors to v1.0.0
Resolve JSON tag name resolution roadmap item: field names in error context now use the json struct tag when available, falling back to the Go field name. Commits MessageProvider interface as stable. Bumps xerrors dependency from v0.9.0 to v1.0.0. API committed as stable.
This commit is contained in:
14
valid.go
14
valid.go
@@ -2,6 +2,8 @@ package valid
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"code.nochebuena.dev/go/xerrors"
|
||||
playground "github.com/go-playground/validator/v10"
|
||||
@@ -33,13 +35,23 @@ func WithMessageProvider(mp MessageProvider) Option {
|
||||
}
|
||||
|
||||
// New returns a Validator. Without options, DefaultMessages (English) is used.
|
||||
// Field names in error context use the json struct tag when available,
|
||||
// falling back to the Go field name.
|
||||
func New(opts ...Option) Validator {
|
||||
cfg := &config{mp: DefaultMessages}
|
||||
for _, o := range opts {
|
||||
o(cfg)
|
||||
}
|
||||
v := playground.New()
|
||||
v.RegisterTagNameFunc(func(fld reflect.StructField) string {
|
||||
name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
|
||||
if name == "" || name == "-" {
|
||||
return fld.Name
|
||||
}
|
||||
return name
|
||||
})
|
||||
return &validator{
|
||||
v: playground.New(),
|
||||
v: v,
|
||||
mp: cfg.mp,
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user