Joi Validation in Javascript— How to translate the errors
Tags: joi, react, node, javascript
Published: 2021-03-03 17:37:51

---
title: Joi Validation in Javascript— How to translate the errors
published: true
description: I will return helpers.error that need to Joi to understand which error is it.
tags: joi, react, nodejs, javascript
//cover_image: https://direct_url_to_image.jpg
---
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](https://github.com/sideway/joi/issues/2566) on Github and I understand how to handle it looking the [test](https://github.com/sideway/joi/blob/master/test/errors.js#L176-L196) that they are made.

As you can see in the documentation the [validate](https://joi.dev/api/?v=17.4.0#anyvalidatevalue-options) 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**_.


```js
import { itErrors, enErrors } from './joiCustomErrors';

const options = {
    errors : {
        labels: false,
        language: localStorage.getItem('i18nextLng')
    },
    messages: {
        it: { ...itErrors },
        en: { ...enErrors }
    }
};

// in this case I get the language tag from a Localhost. 
// my two possible tags are just 'it' and 'en'

const res = mySchema.validate(payload, options);
```
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:
```js
export const itErrors = {
    'string.empty': 'Non può essere vuoto',
    'number.base': 'Deve essere un numero',
    'any.invalid': 'Valore non valido',
    'domain.invalid': 'Dominio non valido',
    'email.invalid': 'Email non valida',
    'phoneNumber.invalid': 'Numero di telefono non valido',
    'array.unique': 'Valore duplicato',
    'custom.max11char': 'Massimo 11 caratteri alfanumerici. Iniziare con una lettera'
};

export const enErrors = {
    'string.empty': 'Cannot be empty',
    'number.base': 'Must be a number',
    'any.invalid': 'Value not valid',
    'domain.invalid': 'Domain not valid',
    'email.invalid': 'Email not valid',
    'phoneNumber.invalid': 'Phone Number not valid',
    'array.unique': 'contains a duplicate value',
    'custom.max11char': 'Maximum 11 alphanumeric characters. Start with a letter'
};
```
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](https://joi.dev/api/?v=17.4.0#anycustommethod-description) 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:

```js
import Joi from 'joi';
import parsePhoneNumber from 'libphonenumber-js';

const isValidPhoneNumber = (phoneNumber, helper) => {
    const res = parsePhoneNumber(phoneNumber, 'IT');
    if (res !== undefined && res.isValid()){
        return phoneNumber;
    }
    return helper.error('phoneNumber.invalid');
};

const voiceSchema = Joi.object({
    'text': Joi.string().required(),
    'voice': Joi.string().allow("")
});

export const phoneNumberSchema = Joi.string().custom(isValidPhoneNumber).required();
export const nameSchema = voiceSchema.required();
export const surnameSchema = voiceSchema.required();

export default Joi.object().keys({
    'name': nameSchema,
    'surname': surnameSchema,
    'phoneNumber':phoneNumberSchema
});
```
Through this pattern Joi will now return the error already translated based on what you have set.

See you next time.