javascript 仅允许 Joi 模式中键的特定值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49007865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:22:15  来源:igfitidea点击:

Allow only specific values for key in Joi schema

javascriptjoi

提问by mardok

Is there any other way to set specific values in Joi validation schema for key except regex pattern?

除了正则表达式模式之外,还有其他方法可以在 Joi 验证模式中为键设置特定值吗?

My example schema:

我的示例架构:

const schema = joi.object().keys({
    query: joi.object().keys({
        // allow only apple and banana
        id: joi.string().regex(/^(apple|banana)$/).required(),
    }).required(),
})

回答by Jiby Jose

You can also use validlike

你也可以使用valid

const schema = joi.object().keys({
  query: joi.object().keys({
    // allow only apple and banana
    id: joi.string().valid('apple','banana').required(),
  }).required(),
})

Reference: https://github.com/hapijs/joi/blob/v13.1.2/API.md#anyvalidvalue---aliases-only-equal

参考:https: //github.com/hapijs/joi/blob/v13.1.2/API.md#anyvalidvalue---aliases-only-equal

回答by anli

If you want to accept one or more values (apple, banana or both) you can use allow: https://hapi.dev/module/joi/api/?v=17.1.1#anyallowvalues

如果你想接受一个或多个值(苹果、香蕉或两者),你可以使用allowhttps: //hapi.dev/module/joi/api/?v=17.1.1#anyallowvalues