首页 > 解决方案 > 是的,对数组下的对象进行验证

问题描述

我正在使用 Formik + Yup 创建带有验证的表单。我有以下初始值。

const initialValue = {
  title: '',
  schedules: [
    {
      maxGame: '',
      bookingDuration: [],
      reservationSlots: [
        {
          from: null,
          to: null,
          increment: '',
          pricePerHours: [
            {
              guest: '',
              price: ''
            }
          ],
          pricePerGame: [
            {
              type: 'Child',
              price: ''
            }
          ]
        }
      ]
    }
  ]
};

我当前的 yup 架构:

const schema = {Yup.object().shape({
              title: Yup.string()
                .min(2, 'Must be 2 characters or more')
                .required('Title is required'),
              schedules: Yup.array().of(
                  Yup.object().shape({
                    bookingDuration: Yup.array().when('maxGame', {
                      is: '',
                      then: Yup.array().min(1, 'Booking Duration is required'),
                      otherwise: Yup.array()
                    }),
                    maxGame: Yup.number().when('bookingDuration', {
                      is: (bookingDuration) => bookingDuration.length === 0,
                      then: Yup.number()
                        .min(1, 'Max Game must be greater than zero')
                        .required('Max Game is required either fill booking duration'),
                      otherwise: Yup.number()
                    }),
                    reservationSlots: Yup.array().of(
                        Yup.object().shape({
                          from: Yup.date().typeError('Invalid Time'),
                          to: Yup.date().typeError('Invalid Time'),
                          increment: Yup.string().required('Time Increment is required'),
                          pricePerGame: Yup.array().of(
                            Yup.object().shape({
                              type: Yup.string(),
                              price: Yup.string()
                                .when(['type'], {
                                  is: (type) => type,
                                  then: Yup.string().required('Price is required'),
                                }),
                            })
                          ),
                        },
                      )
                  },
                  [['bookingDuration', 'maxGame']])
                )
            })
        }

我想要以下验证:

  1. 需要 bookingDuration 和 maxGame 之一。
  2. 如果 bookingDuration.length > 0 则应要求 pricePerHours 的价格。
  3. 如果 pricePerHours 的价格已填写,则应该需要 bookingDuration。
  4. 如果 maxGame !== '' 那么 pricePerGame 的价格应该是必需的。
  5. 如果 pricePerGame 的价格被填满,那么 maxGame 应该是必需的。

我可以申请没有。1 验证,但其余无法应用验证。你能帮我解决这个问题吗?

标签: reactjsformikyup

解决方案


推荐阅读