使用 Yup 和 Formik 根据另一个字段的值检查字段值

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

我正在尝试使用 yup 来检查字段

industryNameOther
是否不为空,但我只想在字段
industryName
(字符串数组)包含字符串“other”时才执行此检查。

我做错了什么?

import * as Yup from 'yup';

const validationSchema = Yup.object({
  sales: Yup.object({
    contactPerson: Yup.string().required('helperText.sales.contactPerson.required'),
  }),
  customer: Yup.object({
    name: Yup.string().required('helperText.customer.name.required'),
    sapNumber: Yup.string()
      .matches(/^4\d{7}$/, 'helperText.customer.sapNumber.format')
      .notRequired(),
    address: Yup.string().required('helperText.customer.address.required'),
    contactPersonMail: Yup.string()
      .email('helperText.customer.contactPersonMail.format')
      .notRequired(),
    industryName: Yup.array().min(1, 'helperText.customer.industryName.number'),
    industryNameOther: Yup.string().when(['industryName'], {
      is: (industryName) => industryName && industryName.includes('other'),
      then: Yup.string().required('helperText.customer.industryNameOther.required'),
    }),
    relations: Yup.number().required('helperText.customer.relations.number').min(0, 'helperText.customer.relations.number')
  }),
  project: Yup.object({
    supplyChainParts: Yup.array().required('helperText.project.supplyChainParts.number').min(1, 'helperText.project.supplyChainParts.number'),
    investmentLocation: Yup.string().required('helperText.project.investmentLocation.required'),
    investmentType: Yup.string().required('helperText.project.investmentType.required')

  })
})

export default validationSchema

我尝试了下面的代码,但它不起作用。

industryNameOther: Yup.string().when(['industryName'], {
      is: (industryName) => industryName && industryName.includes('other'),
      then: Yup.string().required('helperText.customer.industryNameOther.required'),
    }),
reactjs validation formik yup
1个回答
0
投票

请尝试这个。

industryNameOther: Yup.string().when('industryName', {
      is: (industryName) => industryName && industryName.includes('other'),
      then: Yup.string().required('helperText.customer.industryNameOther.required'),
    }),
© www.soinside.com 2019 - 2024. All rights reserved.