Allow registering translations without a Validate instance #1079
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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 tout.Translator
, and register aTranslationFunc
for each tag inValidate
.This method prevents creating new
Validate
instances using the sameut.Translator
, as a second instantiation would try to add again each translation, which would return anErrConflictingTranslation
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 withut.Translator
, and also creates aRegisterDefaultTranslationsFunc(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 newValidate
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 newValidate
instance I create, I callvalidate.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