英文:
Joi custom validation extension not being applied
问题
我一直在简化我的自定义验证函数,试图让它工作,但我一直不成功。以下是我在自定义 joi.ts
中的代码:
const Joi = require('joi')
const joiExtended = Joi.extend({
type: 'address',
base: Joi.string(),
messages: {
'address.invalid': '无效',
},
rules: {
address: {
validate: (value, helpers) => {
console.log('验证地址', value)
// 作为测试,对所有输入都失败
return { value, errors: helpers.error('address.invalid') }
},
},
},
// 在这里添加进一步的扩展
})
console.log(joiExtended.attempt('x', joiExtended.address()))
console.log(joiExtended.attempt('foo', joiExtended.number()))
当我在命令行中运行 node joi.ts
时,我看到:
- 从不打印
验证地址
到控制台 x
确实 打印到控制台- 对
foo
进行的数值合理检查会引发Error [ValidationError]: "value" 必须是一个数字
我在 MacOS Monterey 上运行的 Joi 版本是 17.6.0。我已经广泛阅读了文档(以及深入研究了源代码)。我感到困惑。
英文:
I've been paring down my already simple custom validation function trying to get it to work but I have been unsuccessful. Here's what i'm down to in my custom joi.ts
:
const Joi = require('joi')
const joiExtended = Joi.extend({
type: 'address',
base: Joi.string(),
messages: {
'address.invalid': 'invalid',
},
rules: {
address: {
validate: (value, helpers) => {
console.log('Validating address', value)
// Fail for all inputs as a test
return { value, errors: helpers.error('address.invalid') }
},
},
},
// Add further extensions here
})
console.log(joiExtended.attempt('x', joiExtended.address()))
console.log(joiExtended.attempt('foo', joiExtended.number()))
When I run this from the command line w/ node joi.ts
I see that:
Validating address
is never printed to the consolex
is printed to the console- Sanity check on
foo
being a number throws withError [ValidationError]: "value" must be a number
I'm running Joi 17.6.0 on MacOS Monterey. I've read through the docs (as well as digging through source code) extensively. I'm at a loss.
答案1
得分: 1
根据文档中的示例,您应该将validate
移出rules
并将其放置在根级:
const joiExtended = Joi.extend({
type: "address",
base: Joi.string(),
messages: {
"address.invalid": "无效",
},
validate: (value, helpers) => {
console.log("验证地址", value);
// 作为测试,对所有输入都失败
return { value, errors: helpers.error("address.invalid") };
},
// 在此添加其他扩展
});
您的当前实现不需要rules
。
英文:
Based on the sample in the documentations, you should move validate
out of rules
and place it in the root :
const joiExtended = Joi.extend({
type: "address",
base: Joi.string(),
messages: {
"address.invalid": "invalid",
},
validate: (value, helpers) => {
console.log("Validating address", value);
// Fail for all inputs as a test
return { value, errors: helpers.error("address.invalid") };
},
// Add further extensions here
});
And you wouldn't need rules
for your current implementation.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论