joi
joi copied to clipboard
Support passing custom template functions
- is this issue currently blocking your project? (yes/no): no
- is this issue affecting a production system? (yes/no): no
Context
- node version: 12-14
- module version: 17
- environment (e.g. node, browser, native): node
- used with (e.g. hapi application, another framework, standalone, ...): hapi app
- any other relevant information:
What problem are you trying to solve?
Support custom functions in joi templates. I can see that the package formula
is used and is passed an internal set of functions here: https://github.com/sideway/joi/blob/master/lib/template.js#L384
I think it would be great if we could supply some custom functions to allow string manipulations like lower
and slice
. This would allow re-use of the label
property
joi
.string()
.label('First name')
.max(50)
.required()
.options({
messages: {
'string.empty': 'Enter your {{lower(#label)}}',
'string.max': '{{#label}} must be {{#limit}} characters or fewer'
}
})
Do you have a new or modified API suggestion to solve the problem?
Not sure. Maybe by creating a new customized instance of the joi module like for extensions?
Or maybe as part of the call to options
joi
.string()
.label('First name')
.max(50)
.required()
.options({
messages: {
'string.empty': 'Enter your {{lower(#label)}}',
'string.max': '{{#label}} must be {{#limit}} characters or fewer'
},
functions: {
slice: (str, start, end) => str.slice(start, end),
lower: (str) => str.toLowerCase(),
...
}
})
I think the solution that passing a function to messages()
to custom message is more nimble. like:
messages({label, limit} => { 'string.empty': `Enter your ${lower(label)}`}
Hope joi to provide this.
@Marsup
Extra functions can be supported with minimal effort, it's already something we're using internally, while what you're suggesting would hardly work (multiple messages) and is way more effort imho.
@Marsup got an API in mind you like for this? The API is the hardest part especially if we want it to be namespace-safe and work with extentions.