【问题标题】:How to validate object with constraint on three keys using Joi?如何使用 Joi 验证对三个键有约束的对象?
【发布时间】:2020-02-29 13:48:21
【问题描述】:

我正在尝试 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 语句来验证这一点。

【问题讨论】:

    标签: javascript json validation object joi


    【解决方案1】:

    使用valid()greater()

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

    stackblitz

    【讨论】:

    • 对象还有一些其他的键。我将不得不使用any.when()
    【解决方案2】:

    我们也可以使用any.when() 来验证这些对象。 我们在any.when() 函数参数中传递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');
    }
    

    输出将是这样的。

    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
    

    【讨论】:

    • 这是唯一有效的对象只有这三个键,我的对象也有一些其他键。所以这种方法行不通
    猜你喜欢
    • 2021-06-26
    • 2021-10-10
    • 2017-08-05
    • 2017-06-04
    • 2019-12-13
    • 2016-10-11
    • 1970-01-01
    • 2019-08-11
    • 2018-02-27
    相关资源
    最近更新 更多