Joi Validation in Javascript— How to translate the errors

Marco Pestrin
2 min readMar 3, 2021

I found a good way to translate errors that return Joi validator. It was a little bit hard to understand by docs so I opened an issue on Github and I understand how to handle it looking the test that they are made.

As you can see in the documentation the validate function is carried out on the schema and accept payload as first parameter and options as second parameter.

errors can also be set among the options to be precise, there is the language key. You must specify in which language you want to receive it.
There are messages key as well. It accepts an object whose keys are the possible values that I will have in errors.language.

Values of these keys will be a specific object, that:

  • keys is our tag error
  • value is the translate. That is the message that validate function will return to us.

This is an example:

I can get the error tag directly from Joi. It’s the value of type in error.details of validate function result.

Joi puts some presets tags, as in the example you can see string.empty and number.base. Anyway I can create it when I handle the error.

For example when I execute the custom method, so I create a function with two input parameters. In that function I will return helpers.error that need to Joi to understand which error is it. And as parameter the tag we’ve want to associate with. The same tag that we’ll use to do a translate.

Check row 9 of this snippet:

Through this pattern Joi will now return the error already translated based on what you have set.

See you next time.

--

--