[英]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.