如何使用Joi验证三个键约束的对象?

时间:2019-11-04 09:08:53

标签: javascript json validation object joi

我正在尝试Joi进行对象验证。
我可以使用any.when()来验证具有两个键约束的对象。
我想验证三个键的约束,例如

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语句来验证这一点。

2 个答案:

答案 0 :(得分:0)

我们还可以使用any.when()来验证那些对象。 我们在Joi.object()函数参数中传递any.when()

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');
}

输出将是这样的。

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

答案 1 :(得分:0)

使用valid()greater()

var schema = Joi.object({
  dynamicPrize: Joi.boolean().valid(true),
  entryFee: Joi.number().greater(0),
  isGold: Joi.boolean().valid(false)
});

stackblitz