[英]How to validate object with constraint on three keys using Joi?
我正在尝试Joi进行 object 验证。
我可以使用any.when()对两个键进行约束来验证 object 。
我想验证三个键的约束,例如
var object = {
dynamicPrize: false,
entryFee: 6,
isGold: false,
someOtherKey: someValue
}
// constraint on three keys
if (object.dynamicPrize && object.entryFee > 0 && !object.isGold) {
throw new Error("This should not happen")
}
我想使用 Joi 而不是if, else
语句来验证这一点。
我们还可以使用any.when()
来验证这些对象。 我们在any.when()
function 参数中传递Joi.object()
。
const Joi = require('@hapi/joi');
const validationSchema = Joi
.object({
dynamicPrize: Joi
.boolean()
.required(),
entryFee: Joi
.number()
.integer()
.min(1)
.required(),
isGold: Joi
.boolean()
.required(),
})
.when(Joi.object({
dynamicPrize: Joi.boolean().valid(true),
entryFee: Joi.number().integer().min(1),
isGold: Joi.boolean().valid(false),
}), {
then: Joi.any().forbidden()
.error(new Joi.ValidationError('', {
message: 'This should not happen',
})),
});
const object1 = {
dynamicPrize: true,
entryFee: 6,
isGold: false,
};
const validateObject1 = validationSchema.validate(object1);
console.log('Object1');
if (validateObject1.error) {
console.error(validateObject1.error);
} else {
console.info('validation success');
}
console.log();
const object2 = {
dynamicPrize: false,
entryFee: 6,
isGold: false,
};
const validateObject2 = validationSchema.validate(object2);
console.log('Object2');
if (validateObject2.error) {
console.error(validateObject2.error);
} else {
console.info('validation success');
}
output 将是这样的。
Object1
{ ValidationError
at Object.<anonymous> (/home/wisnu/Labs/nodejs/joi/index.js:23:14)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
_original: undefined,
details: { message: 'This should not happen' } }
Object2
validation success
使用valid()
和greater()
var schema = Joi.object({
dynamicPrize: Joi.boolean().valid(true),
entryFee: Joi.number().greater(0),
isGold: Joi.boolean().valid(false)
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.