gin validator

臺北下了雪發表於2021-11-14
package validator

//gin > 1.4.0

//將驗證器錯誤翻譯成中文

import (
    "github.com/go-playground/locales/zh"

    "github.com/gin-gonic/gin/binding"

    ut "github.com/go-playground/universal-translator"

    "github.com/go-playground/validator/v10"

    translation "github.com/go-playground/validator/v10/translations/zh"
)

var trans ut.Translator

func init() {

    trans, _ = ut.New(zh.New()).GetTranslator("zh")

    translation.RegisterDefaultTranslations(binding.Validator.Engine().(*validator.Validate), trans)

}

func Error(err error) (msg string) {

    if validationErrors, ok := err.(validator.ValidationErrors); !ok {

        return err.Error()

    } else {
        msg = validationErrors[0].Translate(trans)

    }

    return msg

}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章