A utility for handling Joi validation with custom multilingual error messages in an Express.js application.
- Multilingual support using
i18next
. - Custom Joi validation messages per language.
- Reusable message mapping utility for easy customization.
- Automatically detect language based on
Accept-Language
header or fallback to a default language.
Clone the repository and install dependencies:
git clone https://github.com/AmirFt04/joi-multilingual-validation.git
cd joi-multilingual-validation
npm install
npm start
Create a POST request: POST: http://localhost:3000/validate Headers: Accept-Language: en (or any other supported language) Content-Type: application/json
Request Example:
{
"title": "",
"content": "content"
}
Example Responses:
- (in English):
{
"error": "Title cannot be empty."
}
- (in Persian):
{
"error": "عنوان وارد شود"
}
- Joi Validation: The utility uses Joi to validate the incoming data.
- Multilingual Messages: Error messages are mapped to different languages using i18next. It detects the language from the Accept-Language header or defaults to English if no language is specified.
- Custom Translations: You can customize the error messages for each language by modifying the translation files in the locales directory.
-
Add New Languages: To add a new language:
- Create a new JSON file in the locales directory (e.g., locales/es.json for Spanish).
- Add translations for each validation message key.
-
Add the New Language to config.requiredLanguages: To ensure the language is preloaded, open the config/config.js file and add the language code to the requiredLanguages array:
module.exports = {
requiredLanguages: ["en", "fa", "es"], // Add "es" for Spanish
};
Feel free to open issues or pull requests if you have suggestions or improvements!
This project is licensed under the MIT License.
You are free to use, modify, and distribute this project, provided you include a copy of the license with your work.
For more details, see the full license text in the LICENSE file.