基于 React、Yup 和 Formik 中其他字段的必填字段

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

account_id
具有值时,我需要使用
mode_of_payment
字段。

account_id
已填写时,我下面的代码仍然无法使
mode_of_payment
成为必需的。
mode_of_payment
不是必填字段,但当您填写该字段时,
account_id
应变为必填字段

import { array, boolean, object, string } from 'yup';

const validationSchema = object().shape({
  remarks: string().nullable(''),
  remittance_items: array().of(
    object().shape({
      id: string().nullable(),
      mode_of_payment_id: object().shape({
        id: string().nullable(),
        name: string().nullable(),
        with_bank_details: boolean(),
      }),
      account_id: object().shape({
        id: string().when('mode_of_payment_id.id', {
          is: (id) => !!id,
          then: string().required('Select an account'),
          otherwise: string().nullable(),
        }),
        name: string().when('mode_of_payment_id.id', {
          is: (id) => !!id,
          then: string().required(''),
          otherwise: string().nullable(),
        }),
      }),
    })
  ),
});
javascript reactjs formik yup
1个回答
0
投票

尝试这样的事情 -

import { array, boolean, object, string } from 'yup';

const validationSchema = object().shape({
  remarks: string().nullable(''),
  remittance_items: array().of(
    object().shape({
      id: string().nullable(),
      mode_of_payment_id: object().shape({
        id: string().nullable(),
        name: string().nullable(),
        with_bank_details: boolean(),
      }),
      account_id: object().shape({
        id: string().when('mode_of_payment_id', {
          is: (mode_of_payment_id) => !!mode_of_payment_id.id,
          then: string().required('Select an account'),
          otherwise: string().nullable(),
        }),
        name: string().when('mode_of_payment_id', {
          is: (mode_of_payment_id) => !!mode_of_payment_id.id,
          then: string().required(''),
          otherwise: string().nullable(),
        }),
      }),
    })
  ),
});

希望这有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.