Skip to content

Instantly share code, notes, and snippets.

@ortense
Created December 30, 2017 01:31
Show Gist options
  • Save ortense/c30136f47c472369b8873baf1c5d411a to your computer and use it in GitHub Desktop.
Save ortense/c30136f47c472369b8873baf1c5d411a to your computer and use it in GitHub Desktop.
const Joi = require('joi')
// @see https://github.com/hapijs/joi/blob/v13.0.2/API.md#extendextension
const customJoi = Joi.extend((joi) => ({
base: joi.number(),
name: 'number',
language: { stringify: 'parse number to string' },
pre(value, state, options) {
if (this._flags.stringify) return value.toString()
return value
},
rules: [{
name: 'stringify',
setup(params) { this._flags.stringify = true },
}]
}))
const schema = Joi.object({
amount: customJoi.number().positive().max(300).stringify().required()
})
const obj = { amount: 200 }
const { error, value } = schema.validate(obj)
console.log(error) // null
console.log(value) // { amount: '200' }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment