Next.js+TypeScript+Formik中如何基于双条件设置Yup验证?
解决Yup条件验证问题:当current为true且endedAt为null时必填endedAt
你的代码存在几个问题,导致无法实现预期的验证规则:
- 箭头函数参数写法错误:
(!current, endedAt)使用了逗号运算符,实际仅会传入endedAt作为参数,正确的参数结构应该是(current, endedAt) - 逻辑判断完全反向:需求是
current为true时触发验证,但代码中写的是!current - 无需在
when的依赖数组中包含endedAt,因为我们要验证的是当current为true时,endedAt必须有值(不能为null)
修正后的验证代码如下:
validationSchema: Yup.object({ title: Yup.string() .trim() .min(1, t('min-length-x', { x: 1 })) .max(128, t('max-length-x', { x: 128 })) .required(t('required')), organizationName: Yup.string() .trim() .min(1, t('min-length-x', { x: 1 })) .max(128, t('max-length-x', { x: 128 })) .required(t('required')), description: Yup.string() .trim() .min(0, t('min-length-x', { x: 0 })) .max(1024, t('max-length-x', { x: 1024 })), endedAt: Yup.date() .when('current', { is: (current) => current === true, then: Yup.date().required(t('required')), // 可选:明确当current为false时允许endedAt为null,逻辑更清晰 otherwise: Yup.date().nullable() }) }),
关键说明:
- 仅将
current作为when的依赖字段,避免不必要的字段监听 - 当
current为true时,强制endedAt为必填项,自动拦截null或未填写的情况 - 添加
otherwise规则可以明确非触发条件下的字段规则,让验证逻辑更严谨
内容的提问来源于stack exchange,提问作者Jacquit Ratongamanahaja
相关产品推荐
相关产品推荐

