Joi替代品未按照验证请求的要求工作

时间:2018-09-24 22:59:31

标签: node.js joi

我正在使用npm模块Joi来验证请求。 这是我的代码,我希望该代码来自请求,因为如果fooReq,则需要invoice_number,但是Joi没有返回错误。

let fooReq = Joi.object({
    city: Joi.string().required(),
    zip: Joi.string().required(),
}).required();

let fooOpt = Joi.object({
    city: Joi.string(),
    state: Joi.string(),
}).optional();


let barSch = {
    invoice_number: Joi.string(),
    shipping: Joi.alternatives()
        .when('invoice_number',
            {
                is: Joi.string(),
                then: fooReq,
                otherwise: fooOpt
            }
        )
};

let request = {
    invoice_number: "123"
};

console.log(Joi.validate(request, barSch));

1 个答案:

答案 0 :(得分:0)

使用when的简单解决方案,来自github

const Joi = require('joi');

const foo = Joi.object({
    city: Joi.string().required(),
    zip: Joi.string().required(),
});

const deliverySchema = Joi.object({
    invoice_number: Joi.string(),
    shipping: foo
        .when('invoice_number', {
            is: Joi.string().required(),
            then: Joi.required()
        })
});

console.log(deliverySchema.validate({ invoice_number: "123346575867879878" }).error)
console.log(deliverySchema.validate({}).error)
console.log(deliverySchema.validate({ shipping: 'foo' }).error)