Fix FieldError in Translate

issue introduced in #707
pull/709/head
卜木 4 years ago committed by xqbumu
parent 9e2ea40380
commit 102c2cb1da
  1. 6
      errors.go
  2. 49
      validator_test.go

@ -61,10 +61,10 @@ func (ve ValidationErrors) Translate(ut ut.Translator) ValidationErrorsTranslati
trans := make(ValidationErrorsTranslations) trans := make(ValidationErrorsTranslations)
var fe *fieldError var fe FieldError
for i := 0; i < len(ve); i++ { for i := 0; i < len(ve); i++ {
fe = ve[i].(*fieldError) fe = ve[i].(FieldError)
// // in case an Anonymous struct was used, ensure that the key // // in case an Anonymous struct was used, ensure that the key
// // would be 'Username' instead of ".Username" // // would be 'Username' instead of ".Username"
@ -73,7 +73,7 @@ func (ve ValidationErrors) Translate(ut ut.Translator) ValidationErrorsTranslati
// continue // continue
// } // }
trans[fe.ns] = fe.Translate(ut) trans[fe.Namespace()] = fe.Translate(ut)
} }
return trans return trans

@ -8,6 +8,7 @@ import (
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"fmt" "fmt"
"log"
"path/filepath" "path/filepath"
"reflect" "reflect"
"strings" "strings"
@ -8953,6 +8954,54 @@ func TestTranslationErrors(t *testing.T) {
Equal(t, err.Error(), "error: conflicting key 'required' rule 'Unknown' with text '{0} is a required field' for locale 'en', value being ignored") Equal(t, err.Error(), "error: conflicting key 'required' rule 'Unknown' with text '{0} is a required field' for locale 'en', value being ignored")
} }
func TestTranslationFieldErrors(t *testing.T) {
type SelfError struct {
FieldError
}
en := en.New()
uni := ut.New(en, en, fr.New())
trans, _ := uni.GetTranslator("en")
validate := New()
err := validate.RegisterTranslation("required", trans,
func(ut ut.Translator) (err error) {
// using this stype because multiple translation may have to be added for the full translation
if err = ut.Add("required", "{0} is a required field", false); err != nil {
return
}
return
}, func(ut ut.Translator, fe FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field())
if err != nil {
fmt.Printf("warning: error translating FieldError: %#v", fe.(*fieldError))
return fe.(*fieldError).Error()
}
return t
})
err = validate.Var("", "required")
NotEqual(t, err, nil)
selfErr := ValidationErrors{}
errs, ok := err.(ValidationErrors)
Equal(t, ok, true)
for _, e := range errs {
selfErr = append(selfErr, e)
}
errTrans := selfErr.Translate(trans)
log.Println(errTrans)
Equal(t, selfErr.Translate(trans), ValidationErrorsTranslations{
"": " is a required field",
})
}
func TestStructFiltered(t *testing.T) { func TestStructFiltered(t *testing.T) {
p1 := func(ns []byte) bool { p1 := func(ns []byte) bool {
if bytes.HasSuffix(ns, []byte("NoTag")) || bytes.HasSuffix(ns, []byte("Required")) { if bytes.HasSuffix(ns, []byte("NoTag")) || bytes.HasSuffix(ns, []byte("Required")) {

Loading…
Cancel
Save