【问题标题】:Joi to validate alternatives depending on multiple keysJoi 根据多个键验证替代方案
【发布时间】:2019-09-08 11:11:00
【问题描述】:

使用Joi,只有当typeAB 并且subTypeAABB 时,我如何使架构需要rent.max?这是我的尝试。

const Joi = require("joi");
const schema = Joi.object().keys({
  type: Joi.string().valid('A', 'B', 'C').required(),
  subType: Joi.string().valid('AA', 'BB', 'X'),
  rent: Joi.object().keys({
    price: Joi.number().required().precision(2),
    // max is allowed only when type is A or B
    // and subType is AA or BB.
    max: Joi.alternatives()
      .when('type', {
        is: Joi.valid('A', 'B'),
        then: Joi.alternatives().when('subType', {
            is: Joi.valid('AA', 'BB'),
            then: Joi.number(),
            otherwise: Joi.forbidden()
        }),
        otherwise: Joi.forbidden()
      })
  })
});
const obj = {
    type: 'A',
    subType: 'AA',
    rent: {
        price: 3000.25,
        max: 300.50,
    }
};
const result = Joi.validate(obj, schema);
console.log(result.error);

我预计验证会失败,但事实并非如此。

【问题讨论】:

    标签: node.js validation schema joi


    【解决方案1】:

    如果你想验证键 typesubType 你的验证必须在对象之后,例如:

    const schema = Joi.object({
            type: Joi.string().valid('A', 'B', 'C'),
            subType: Joi.string().valid('AA', 'BB', 'X'),
            rent: Joi.object({
                amount: Joi.number(),
                price: Joi.number().required().precision(2),
            })
        }).when(Joi.object({
            type: Joi.string().valid('A', 'B').required(),
            subType: Joi.string().valid('AA', 'BB').required()
        }).unknown(), {
            then: Joi.object({
                rent: Joi.object({
                    amount: Joi.number().required()
                })
            }),
            otherwise: Joi.object({
                rent: Joi.object({
                    amount: Joi.forbidden()
                })
            })
        });
    

    这是以下示例的结果:

    // FAIL - requires amount
       const obj = {
            type: 'A',
            subType: 'BB',
            rent: {
                price: 10
            }
        };
    
    // FAIL - amount is not allowed
        const obj = {
            type: 'A',
            subType: 'X',
            rent: {
                amount: 3000.25,
                price: 300.50
            }
        };
    
    
    // SUCCESS
        const obj = {
            type: 'A',
            subType: 'BB',
            rent: {
                amount: 3000.25,
                price: 300.50
            }
        };
    
    // SUCCESS
       const obj = {
            type: 'A',
            subType: 'X',
            rent: {
                price: 300.50
            }
    
        };
    

    【讨论】:

      猜你喜欢
      • 2019-02-25
      • 2019-06-04
      • 1970-01-01
      • 2021-11-30
      • 2022-01-08
      • 2014-12-18
      • 2019-07-08
      • 2014-02-24
      • 1970-01-01
      相关资源
      最近更新 更多