gpt4 book ai didi

node.js - Joi 字段验证基于另一个字段的一组值

转载 作者:行者123 更新时间:2023-12-04 12:05:47 25 4
gpt4 key购买 nike

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

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())
});

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

最佳答案

我终于通过尝试得到了它:

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

关于node.js - Joi 字段验证基于另一个字段的一组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61912282/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com