问题描述
我尝试验证以下 JSON:
"flight": true,"hotel": false,"car": false,"flightReservation": {
"type": "depart-return","flights": [
{
"fromTown": "Paris","toTown": "Barcelona",}
]
},}
使用条件逻辑。仅当“flight”为真时才需要“flightReservation”。
我使用以下 yup 模式来尝试验证:
const yup = require("yup");
const flightsSchema = yup.object({
fromTown: yup.string().required(),toTown: yup.string().required()
});
const flightReservationSchema = yup.object().shape({
type: yup.string(),flights: yup.array().of(flightsSchema),});
const reservationSchema = yup.object({
flight: yup.boolean().required(),hotel: yup.boolean().required(),car: yup.boolean().required(),flightReservation: flightReservationSchema.when("flight",{
is: true,then: flightReservationSchema.required(),}),});
module.exports = reservationSchema;
但它不起作用,即使没有“flightReservation”对象,我也可以发送json。如果我将“flightReservation”更改为字符串而不是对象,例如
flightReservation: yup.string().when("flight",then: yup.string().required(),
效果很好,如果没有“flightReservation”,我无法发送带有“flight”的JSON:true。
谢谢!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)