使用 yup 以条件逻辑验证 json 内容

问题描述

我尝试验证以下 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 (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...