ortense
12/30/2017 - 1:31 AM

Joi.number.stringify.js

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' }