简体   繁体   English

如何使用 Joi 对三个键进行约束来验证 object?

[英]How to validate object with constraint on three keys using Joi?

I am trying Joi for object validation.我正在尝试Joi进行 object 验证。
I can validate object with constraint on two key using any.when() .我可以使用any.when()对两个键进行约束来验证 object 。
I want to validate with constraint on three keys eg我想验证三个键的约束,例如

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")
}

I want to validate this using Joi instead of if, else statement.我想使用 Joi 而不是if, else语句来验证这一点。

We could also use any.when() for validating those objects.我们还可以使用any.when()来验证这些对象。 We pass Joi.object() in the any.when() function argument.我们在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');
}

The output will be something like this. 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

Using valid() and greater()使用valid()greater()

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

stackblitz 堆栈闪电战

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM