基于另一个字段的一组值的Joi字段验证

问题描述 投票:0回答:1

我正在尝试根据另一个字段的一组值来验证对象中的字段。假设我的对象必须包含字段field1field2。字段1可以取值A,B,C,D,E,F,H,I。现在说一说field1是否为任何值;否则,取值为0。 A,B,C,H,那么field2应该为空。我该怎么做呢。我认为它应该在下面有Synthax,但我不知道如何完全实现它。

const mySchema = Joi.object({
   field1: Joi.string().valid('A','B','C','D','E','F','H','I').required(),
   field2: Joi.when('field1', is: <A or B or C or H> then: <field2 should be null> otherwise: Joi.date().required())
});

NB:我正在使用"@hapi/joi": "^17.1.1"

node.js express validation switch-statement joi
1个回答
0
投票

我终于尝试了:

const Joi = require("@hapi/joi");

const schema = Joi.object({
    field1: Joi.string().valid('A', 'B', 'C', 'D', 'E', 'F', 'H', 'I').required(),
    field2: Joi.when('field1', {
        is: Joi.string().valid('A', 'B', 'C', 'H'),
        then: Joi.valid(null),
        otherwise: Joi.date().required(),
    }),
});

const validation = [schema.validate({ field1: 'B', field2: null }), schema.validate({ field1: 'E', field2: null }),
                    schema.validate({ field1: 'E', field2: Date() }), schema.validate({ field1: 'A', field2: Date() })];

validation.forEach((v)=>{
    if(v.error){
        console.log(JSON.stringify(v.error));
    }else{
        console.log(JSON.stringify(v.value));
    }
});

这里是输出。

{"field1":"B","field2":null}
{"_original":{"field1":"E","field2":null},"details":[{"message":"\"field2\" must be a valid date","path":["field2"],"type":"date.base","context":{"label":"field2","value":null,"key":"field2"}}]}
{"field1":"E","field2":"2020-05-20T12:26:48.000Z"}
{"_original":{"field1":"A","field2":"Wed May 20 2020 13:26:48 GMT+0100 (West Africa Standard Time)"},"details":[{"message":"\"field2\" must be [null]","path":["field2"],"type":"any.only","context":{"valids":[null],"label":"field2","value":"Wed May 20 2020 13:26:48 GMT+0100 (West Africa Standard Time)","key":"field2"}}]}
© www.soinside.com 2019 - 2024. All rights reserved.