【发布时间】:2022-01-17 11:00:57
【问题描述】:
假设我有 3 个字段:showDiscount、discountType 和 discountValue。
当showDiscount 设置为true 且discountType 为“PERCENTAGE”时,discountValue 应为必填项且应为1 到100。如果discountType 为“FIXED_AMOUNT”,discountValue 应至少为0.01.
我尝试寻找解决方案,这是我能找到的最接近的解决方案:Two Condition in When in Yup in React
应用更改后,这里是一个示例 sn-p:
const schema = yup.object().shape({
showDiscount: yup.boolean().required(''),
discountType: yup.string().when('showDiscount', {
is: true,
then: yup.string().required(),
}),
discountValue: yup.number().when('showDiscount', {
is: (showDiscount) => showDiscount,
then: yup
.number()
.when('discountType', (discountType, discountValueSchema) => {
switch (discountType) {
case 'PERCENTAGE':
return discountValueSchema
.typeError('Enter a number')
.min(1, 'Enter a discount percentage of at least 1%')
.max(100, 'Enter a discount percentage of at most 100%')
case 'FIXED_AMOUNT':
return discountValueSchema
.typeError('Enter a number')
.min(0.01, 'Enter a discount amount of at least 0.01')
default:
return discountValueSchema
}
}),
})
),
})
当我尝试提交表单时,无论showDiscount 和discountType 的值如何,我都会收到以下错误:
discountValue 必须是
number类型,但最终值为:NaN(从值""转换)。
【问题讨论】:
标签: reactjs validation yup