是的验证,如果一个字段为真,使用 switch 语句检查另一个字段的值
Yup validation, if a field is true, check the value of another field with switch statements
假设我有 3 个字段:showDiscount
、discountType
和 discountValue
。
当showDiscount
设置为true且discountType
为'PERCENTAGE'时,discountValue
应该是必需的并且应该是从1到100。如果discountType
是 'FIXED_AMOUNT',discountValue
至少应该是 0.01。
我尝试寻找解决方案,这是我能找到的最接近的解决方案:
应用更改后,这是一个示例片段:
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 must be a number
type, but the final value was: NaN
(cast from the value ""
).
when
可以接受多个字段,所以你应该可以做到
...
.when(['showDiscount', 'discountType'], (showDiscount, discountType, discountValueSchema) => {
...
虽然文档中没有明确说明此示例,但您可以在此处看到提示 https://www.npmjs.com/package/yup#mixedwhenkeys-string--arraystring-builder-object--value-schema-schema-schema
假设我有 3 个字段:showDiscount
、discountType
和 discountValue
。
当showDiscount
设置为true且discountType
为'PERCENTAGE'时,discountValue
应该是必需的并且应该是从1到100。如果discountType
是 'FIXED_AMOUNT',discountValue
至少应该是 0.01。
我尝试寻找解决方案,这是我能找到的最接近的解决方案:
应用更改后,这是一个示例片段:
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 must be a
number
type, but the final value was:NaN
(cast from the value""
).
when
可以接受多个字段,所以你应该可以做到
...
.when(['showDiscount', 'discountType'], (showDiscount, discountType, discountValueSchema) => {
...
虽然文档中没有明确说明此示例,但您可以在此处看到提示 https://www.npmjs.com/package/yup#mixedwhenkeys-string--arraystring-builder-object--value-schema-schema-schema