validator
validator copied to clipboard
FieldError.Field() doesn't work
- [x] I have looked at the documentation here first?
- [x] I have looked at the examples provided that may showcase my question here?
Package version:
v10
Issue, Question or Enhancement:
Method Field() of FieldError doesn't work according to documentation:
// Field returns the fields name with the tag name taking precedence over the
// field's actual name.
//
// eq. JSON name "fname"
// see StructField for comparison
Field() string
Code sample, to showcase or reproduce:
type Struct struct {
Field string `json:"json_field" validate:"required"`
}
func TestField(t *testing.T) {
v := validator.New()
s := &Struct{}
err := v.Struct(s)
valErrs := err.(validator.ValidationErrors)
requiredErr := valErrs[0]
fmt.Println(requiredErr.Field())
}
The output is Field, according to documentation it should be json_field
I confirm this behave
However this should do the trick
v := validator.New()
v.RegisterTagNameFunc(func(fld reflect.StructField) string {
name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
if name == "-" {
return ""
}
return name
})
ref:
- https://github.com/go-playground/validator/blob/master/validator_test.go#L8285-L8326
- https://pkg.go.dev/github.com/go-playground/validator/v10#Validate.RegisterTagNameFunc
I stumbled upon this issue today and if anybody needs to use it in gin framework, here's how:
router := gin.Default()
if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
v.RegisterTagNameFunc(func(fld reflect.StructField) string {
name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
if name == "-" {
return ""
}
return name
})
}
works like a charm, thanks a lot @grandeto !