Created
December 30, 2017 01:31
-
-
Save ortense/c30136f47c472369b8873baf1c5d411a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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