go-playground / validator

:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving
MIT License
16.41k stars 1.31k forks source link

Allow registering translations without a Validate instance #1079

Open RangelReale opened 1 year ago

RangelReale commented 1 year ago

Fixes Or Enhances

The function Validate.RegisterTranslation(tag string, trans ut.Translator, registerFn RegisterTranslationsFunc, translationFn TranslationFunc) (err error) does 2 things: it adds tags translations to ut.Translator, and register a TranslationFunc for each tag in Validate.

This method prevents creating new Validate instances using the same ut.Translator, as a second instantiation would try to add again each translation, which would return an ErrConflictingTranslation error, and none of the translations functions would be set.

This PR creates a Validate.RegisterTranslationsFunc(trans ut.Translator, translationsFn map[string]TranslationFunc) function which allows setting the translation functions for each tag without registering with ut.Translator, and also creates a RegisterDefaultTranslationsFunc(trans ut.Translator) (map[string]validator.TranslationFunc, error) for each language which returns a map of the tag=>TranslationFunc, which can be sent on the new Validate method.

The current RegisterDefaultTranslations method for the languages keeps working as today, calling both of the new functions, so it is totally compatible with the current implemenation.

With this change, I can call tf, err := en_translations.RegisterDefaultTranslationsFunc(trans) a single time during initialization, and for each new Validate instance I create, I call validate.RegisterTranslationsFunc(trans, tf), reusing all the language loading.

This initial PR just updates the english language, I will update all others if this is ok.

Make sure that you've checked the boxes below before you submit PR:

@go-playground/validator-maintainers

coveralls commented 1 year ago

Coverage Status

Coverage: 74.123% (-0.07%) from 74.191% when pulling 8b0d4fa1e1f5c7ccb274615c486b3f8e61bb18f8 on RangelReale:translator-func into 8f07b0368280d9fc70b4ffd3708b31427bbc286d on go-playground:master.