问题描述
我有这个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',otherwise: yup.number().moreThan(yup.ref('min_amount'),'max_amount must be greater than minimum amount'),});
问题在于它会引发此错误:
错误:循环依赖,节点为:“ 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',otherwise: yup.number().moreThan(yup.ref('min_amount'),'max_amount must be greater than minimum amount'),},['max_amount','min_amount']);