[英]Error: Cyclic dependency with Yup Validation
我有这个 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(),
});
问题是它引发了这个错误:
错误:循环依赖,节点为:“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']);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.