gpt4 book ai didi

javascript - 错误 : Cyclic dependency with Yup Validation

转载 作者:行者123 更新时间:2023-12-05 01:10:34 25 4
gpt4 key购买 nike

我有这个 Yup 验证模式,其中包括对 min_amount 和 max_amount 值的检查。我在 ReactJS 表单上使用它。

const amountsSchema = yup.object({
min_amount: yup.number()
.max(999999999999999)
.nullable()
.transform((v, o) => (o === '' ? null : v))
.typeError('min_amount must be a number')
.when('max_amount', {
is: '',
then: yup.number().min(1),
otherwise: yup.number().lessThan(yup.ref('max_amount'), 'min_amount must be less than maximum amount'),
})
.required(),

max_amount: yup.number()
.max(999999999999999)
.nullable()
.transform((v, o) => (o === '' ? null : v))
.typeError('max_amount must be a number')
.when('min_amount', {
is: '',
then: yup.number().min(1),
otherwise: yup.number().moreThan(yup.ref('min_amount'), 'max_amount must be greater than minimum amount'),
})
.required(),
});

问题是它引发了这个错误:

Error: Cyclic dependency, node was:"max_amount"

如何正确编写架构,以便无论用户首先/最后填写哪个字段,架构都可以在用户填写表单时正确比较这两个字段?启发我写成这样的是以前的时候是这样的:

const amountsSchema = yup.object({
min_amount: yup.number()
.min(1)
.max(999999999999999)
.nullable()
.transform((v, o) => (o === '' ? null : v))
.typeError('min_amount must be a number')
.required(),

max_amount: yup.number()
.min(1)
.max(999999999999999)
.nullable()
.transform((v, o) => (o === '' ? null : v))
.typeError('max_amount must be a number')
.moreThan(yup.ref('min_amount'), 'max_amount must be greater than minimum amount')
.required(),
});

用户可以先填写 max_amount,然后填写更大的 min_amount 并绕过验证。

最佳答案

我觉得你可以试试

const amountsSchema = yup.object().shape({
min_amount: yup.number()
.max(999999999999999)
.nullable()
.transform((v, o) => (o === '' ? null : v))
.typeError('min_amount must be a number')
.when('max_amount', {
is: '',
then: yup.number().min(1),
otherwise: yup.number().lessThan(yup.ref('max_amount'), 'min_amount must be less than maximum amount'),
})
.required(),

max_amount: yup.number()
.max(999999999999999)
.nullable()
.transform((v, o) => (o === '' ? null : v))
.typeError('max_amount must be a number')
.when('min_amount', {
is: '',
then: yup.number().min(1),
otherwise: yup.number().moreThan(yup.ref('min_amount'), 'max_amount must be greater than minimum amount'),
})
.required(),
}, ['max_amount', 'min_amount']);

关于javascript - 错误 : Cyclic dependency with Yup Validation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64020518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com