首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Joi需要未知字段

Joi需要未知字段
EN

Stack Overflow用户
提问于 2020-10-29 20:22:29
回答 1查看 201关注 0票数 0

我正在验证一个GET请求查询字符串(使用express-joi-validation),并要求用户传递至少一个没有在模式中直接指定的额外键值对。

我试着验证如下:

代码语言:javascript
复制
const schema = Joi
    .object({
        requiredKey: Joi.string().required()
        knownExtraKey: Joi.boolean()
    })
    .pattern(/^/, Joi.string().required())

schema.validate({requiredKey: 'A'}) // valid but shouldn't be
schema.validate({requiredKey: 'A', name: "paul"}) // valid
EN

回答 1

Stack Overflow用户

发布于 2020-10-30 01:59:50

如果至少需要一个属性,请执行以下操作:

joi版本17.2.1

解释:

您需要使用以下公式指定最小密钥object().min()所需属性的数量+ 1。在下面的示例中,如果您验证一个具有3个或4个属性的对象,则验证不会返回任何错误。

代码语言:javascript
复制
const Joi = require('joi');

const schema = Joi.object().keys({
  one: Joi.string().required(),
  two: Joi.string().required(),
  three: Joi.string(),
  four: Joi.string(),
}).min(3);

// works
const data1 = {
  one: 'one',
  two: 'two',
  three: 'three',
};
console.log(schema.validate(data1).error);

// works
const data2 = {
  one: 'one',
  two: 'two',
  three: 'three',
  four: 'four',
};
console.log(schema.validate(data2).error);

// fails
const data3 = {
  one: 'one',
  two: 'two',
};
console.log(schema.validate(data3).error)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64591038

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档