错误:具有Yup验证的循环依赖性

问题描述

我有这个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']);

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...