如何使用不同形状内另一个模式的字段值来验证一个模式中的字段?

问题描述 投票:0回答:1
const validationSchema = Yup.object().shape({
 RecipientDetail: Yup.object().shape({
  EmployeeOfferAndCoverage: Yup.object().shape({
  MonthlyOfferCoverageGrp: Yup.object().shape({
    AllOfferCd: Yup.string(),
  }),
  MonthlyEmployeeRequiredContriGrp: Yup.object().shape({
    AllMonthAmt: Yup.number().when(
      'RecipientDetail.EmployeeOfferAndCoverage.MonthlyOfferCoverageGrp.AllOfferCd', 
      {
        is: (val) => val !== undefined && val !== null && val !== '',  // Check if 
   AllOfferCd has a value
        then: Yup.number()
          .max(3500, 'Amount cannot exceed 3500')
          .nullable(),  // Allow null if condition is not met
        otherwise: Yup.number().nullable(), // Allow null for other cases
       }
      ),
     }),
    }),
  }),
 });

我已获取此引用的值“RecipientDetail.EmployeeOfferAndCoverage.MonthlyOfferCoverageGrp.AllOfferCd”未定义。我无法解决这个问题

reactjs yup
1个回答
0
投票

这里的问题是 Yup 的

.when
条件仅限于同一形状级别内的字段,因此它无法直接访问另一个模式中深度嵌套的字段。

要解决此问题,您可以使用 Yup 的

.test
方法,该方法允许使用自定义验证函数,您可以在其中访问架构中的所有值。以下是修改架构的方法:


const validationSchema = Yup.object().shape({
  RecipientDetail: Yup.object().shape({
    EmployeeOfferAndCoverage: Yup.object().shape({
      MonthlyOfferCoverageGrp: Yup.object().shape({
        AllOfferCd: Yup.string(),
      }),
      MonthlyEmployeeRequiredContriGrp: Yup.object().shape({
        AllMonthAmt: Yup.number()
          .nullable()
          .test(
            'maxAmountIfOfferCdExists',
            'Amount cannot exceed 3500',
            function (value) {
              const { RecipientDetail } = this.parent.parent.parent; // Access the root object
              const AllOfferCd = RecipientDetail?.EmployeeOfferAndCoverage?.MonthlyOfferCoverageGrp?.AllOfferCd;
              
              if (AllOfferCd) {
                // Only validate max when AllOfferCd has a value
                return value === null || value <= 3500;
              }
              return true; // Otherwise, allow any value including null
            }
          ),
      }),
    }),
  }),
});
© www.soinside.com 2019 - 2024. All rights reserved.