When using in conjunction with Hapi, is there anyway to override the language settings on a global level. I know I can set language options on each field validated, but that is tedious if I wanted to change the language for all fields everywhere in my app.
I know that somewhere Hapi is calling Joi.validate() which allows a language option to be passed in, is there anyway to configure that?
Yup, just put that in a file and use it as your joi base :
var Joi = require('joi');
module.exports = Joi.options({ language: { ... } })
var Joi = require('./myOwnJoi');
var schema = Joi.object()...
You can probably also set it in the server options, see routes parameter. Routes accept a validate.options, so something like { connections: { routes: { validate: { options: { language: {...}}}}}} should do. (not tested)
Apparently the first approach doesn't work anymore. The object returned by the Joi.options() doesn't have any object() or string() functions for example, so, we can't do module.exports = Joi.options({ language: { ... } }), otherwise, we get a TypeError: Joi.options(...).object is not a function
Yup I was wrong, it would never have worked. Last answer should work though.
But last answer doesn't work with Joi standalone. Any other alternatives?
Same as @EdsonBueno still have question on how to apply my own language options to global standalone joi object? Any approach or workaround for today?
It can now be done with https://github.com/hapijs/joi/blob/master/API.md#defaultsfn, applying the same language to any type of schema.
It can now be done with https://github.com/hapijs/joi/blob/master/API.md#defaultsfn, applying the same language to any type of schema.
how ?
It can now be done with https://github.com/hapijs/joi/blob/master/API.md#defaultsfn, applying the same language to any type of schema.
I've done it following way :)
// SEE language.js for message structure.
// https://github.com/hapijs/joi/blob/master/lib/language.js
const ja = require('./locales/ja') // Use "Japanese" locale in my case.
const assert = require('assert')
// `error.message` should be original one.
assert.strictEqual(Joi.validate('boom', Joi.string().email()).error.message, '"value" must be a valid email')
// Inject localized error messages into Joi instance.
const LocalisedJoi = Joi.defaults((schema) => {
return schema.options({
language: ja.errors
})
})
// `error.message` should be localized version now!
assert.notStrictEqual(LocalisedJoi.validate('boom', LocalisedJoi.string().email()).error.message, '"value" must be a valid email')
@subuta It's funny that I also needed to override the global language and I found your comment that was posted just 26 minutes ago.
Thanks for sharing your solution.
Most helpful comment
But last answer doesn't work with Joi standalone. Any other alternatives?