我正在验证一个GET请求查询字符串(使用express-joi-validation),并要求用户传递至少一个没有在模式中直接指定的额外键值对。
我试着验证如下:
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发布于 2020-10-30 01:59:50
如果至少需要一个属性,请执行以下操作:
joi版本17.2.1
解释:
您需要使用以下公式指定最小密钥object().min():所需属性的数量+ 1。在下面的示例中,如果您验证一个具有3个或4个属性的对象,则验证不会返回任何错误。
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)https://stackoverflow.com/questions/64591038
复制相似问题