I know in the validator.v9,it has the function of Translations & Custom Errors
now I see gin v1.5.0 has upgraded validator to v9, but I didn't find out some examples about
Translations & Custom Errors in gin.
can anyone help me,thanks in advance.
There is an example in the validators repo like you mentioned. To mix it in with gin you just have to access the underlying validator engine to set it up:
import (
"github.com/gin-gonic/gin/binding"
"github.com/go-playground/locales/en"
ut "github.com/go-playground/universal-translator"
en_translations "gopkg.in/go-playground/validator.v9/translations/en"
)
...
var trans ut.Translator
...
if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
en := en.New()
uni := ut.New(en, en)
// this is usually know or extracted from http 'Accept-Language' header
// also see uni.FindTranslator(...)
trans, _ = uni.GetTranslator("en")
en_translations.RegisterDefaultTranslations(v, trans)
}
...
and then when you validate:
...
type IceCream struct {
Title string `json:"title" binding:"required,min=4,max=30"`
}
var iceCream IceCream
if err := c.ShouldBindJSON(&iceCream); err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
"error" : err.(validator.ValidationErrors).Translate(trans),
})
return
}
...
Its basically just copying and pasting some code from both repos, so that all the pieces come together. Best of luck!
@swrap Thank you very much.It's an elegant solution.
Most helpful comment
There is an example in the validators repo like you mentioned. To mix it in with gin you just have to access the underlying validator engine to set it up:
and then when you validate:
Its basically just copying and pasting some code from both repos, so that all the pieces come together. Best of luck!