validate
validate copied to clipboard
Dynamic translation of validation errors
Hi everybody !
I am facing a little issue with the translations of the validation errors.
I see it is possible to add a static translation by adding a Message field in the validator, like this:
&validators.EmailIsPresent{Name: "Email", Field: u.Email, Message: "Mail is not in the right format."}
This works great for a static translation, but what about dynamic translations (based on the user language) ?
In actions, I know I can use this method: T.Translate(c, "users.login-success")
but in models (where I don't have access to the context), I can't use that.
Is there any solution to solve this issue ?
Thanks a lot !
I solved this by returning the translation ID from the validation and then use the following helper function in the action like this:
// Add validation error in the model.
errors.Add(validators.GenerateKey("LocationID"), "locationsContact.existsError")
// Make the translated errors available inside the html template
c.Set("errors", translateValidationErr(c, verrs))
// translateValidationErr is a helper function to translate validation errors returned from the model.
func translateValidationErr(c buffalo.Context, verrs *validate.Errors) *validate.Errors {
tverrs := validate.NewErrors()
for key, value := range verrs.Errors {
for _, msg := range value {
tverrs.Add(key, T.Translate(c, msg))
}
}
return tverrs
}
If there exists a translation for the translation error msg (which is used as translation ID), this is returned in the correct language. If this is not the case, the original error message is returned unaltered, which preserves the current behavior.
Yeah, I think @breml's approach is nice since the Model layer can be slimmer and can stay focused on the database-specific jobs. I think there are many different kinds of developers, someone love Controller(or Action)-driven development while some others love Model-driven development style. So it could be up to you.
I will leave this issue open so we can hear others' opinions if they share their thought.
This issue is stale because it has been open 30 days with no activity. Remove stale label or comment. Otherwise, this will be closed in 7 days.
This issue was closed because it has been stalled for 30+7 days with no activity.