问题描述
当前验证:
const myPacket = Joi.object({
cost: Joi.number().precision(2).required()
})
这里,我如何检查我的 cost
字段是否是 0.25
的倍数?因此,例如,cost
的有效值为 1.25、2.5、2.25 等。
解决方法
您可以使用自定义方法并在那里编写自己的逻辑https://github.com/sideway/joi/blob/master/API.md#anycustommethod-description
示例
const Joi = require('joi')
const myCustomValidation = (value,helpers) => {
if (typeof value !== 'number') return helpers.error('any.invalid')
if (parseFloat(value*4) % 1 === 0) {
// your logic above
return value
} else return helpers.error('any.invalid')
}
const schema = Joi.object({
customField: Joi.number().custom(myCustomValidation,'my custom validation description')
})
schema.validate({customField: 1.25})
schema.validate({customField: 1.251})