跨层级Yup Schema字段验证求助:引用字段值为undefined
问题原因及解决方案
你的问题出在Yup when 方法中引用字段的路径错误。在嵌套Schema中,when 的路径是相对于当前字段所在的Schema层级,而非全量的根路径。你使用的全路径RecipientDetail.EmployeeOfferAndCoverage.MonthlyOfferCoverageGrp.AllOfferCd会被Yup解析为当前层级(MonthlyEmployeeRequiredContriGrp)下的子路径,自然找不到对应字段,导致值始终为undefined。
两种可行的修复方式:
1. 使用相对路径
由于MonthlyEmployeeRequiredContriGrp和MonthlyOfferCoverageGrp是同级(都属于EmployeeOfferAndCoverage),可以用相对路径引用目标字段:
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( '../MonthlyOfferCoverageGrp.AllOfferCd', // 相对路径,指向同级的MonthlyOfferCoverageGrp { is: (val) => !!val, // 简化判断,空值/undefined/null都会返回false then: Yup.number() .max(3500, 'Amount cannot exceed 3500') .nullable(), otherwise: Yup.number().nullable(), } ), }), }), }), });
2. 使用根路径前缀$
如果你偏好使用全路径,可以在路径前加$表示从根Schema开始解析:
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, then: Yup.number() .max(3500, 'Amount cannot exceed 3500') .nullable(), otherwise: Yup.number().nullable(), } ), }), }), }), });
额外优化点
- 你原来的
is判断可以简化为!!val,它会自动排除undefined、null和空字符串; - 由于
then和otherwise都包含.nullable(),可以把这个规则提到外层,减少重复代码:
AllMonthAmt: Yup.number() .nullable() .when( '../MonthlyOfferCoverageGrp.AllOfferCd', { is: (val) => !!val, then: (schema) => schema.max(3500, 'Amount cannot exceed 3500'), } ),
内容的提问来源于stack exchange,提问作者subbu
相关产品推荐
相关产品推荐

