Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow registering translations without a Validate instance #1079

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

RangelReale
Copy link

@RangelReale RangelReale commented Mar 3, 2023

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:

  • Tests exist or have been written that cover this particular change.

@go-playground/validator-maintainers

@RangelReale RangelReale requested a review from a team as a code owner March 3, 2023 20:10
@coveralls
Copy link

Coverage Status

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants