获取另一个字段的值以在 Yup Schema 中进行验证

Mic*_*rds 8 javascript yup formik

我正在使用 Formik 和 Yup 进行验证和 TypeScript

我有一个字段需要根据另一个字段的值进行验证。

第一个字段称为价格,第二个字段称为提示。最大小费值是输入价格的 10%。

我尝试使用以下方法为此创建验证:

   tips: yup.number()
    .min(0, `Minimum tip is $0`)
    .max( parseFloat(yup.ref('price'))* 0.1, "Maximum tip is 10% of the price.");
Run Code Online (Sandbox Code Playgroud)

但是这不会编译,因为 yup.ref 返回一个 Ref。如何在此验证中获取 price 字段的值?

小智 16

如果您不想使用this.parent访问其他属性值,您可以使用context

tips: number()
.min(0, `Minimum tip is $0`)
.test(
  'max',
  '${path} must be less than 10% of the price',
  (value, context) => value <= parseFloat(context.parent.price * 0.1),
),

// OR

tips: number()
.min(0, `Minimum tip is $0`)
.test({
      name: 'max',
      exclusive: false,
      params: { },
      message: '${path} must be less than 10% of the price',
      test: (value, context) => value <= parseFloat(context.parent.price * 0.1),
    }),
Run Code Online (Sandbox Code Playgroud)


tat*_*oto 13

number.max 无法引用其他字段并在验证时使用它进行计算。

如果要执行此操作,则需要使用mixed.test.
这是一个例子。

  tips: number()
    .min(0, `Minimum tip is $0`)
    .test({
      name: 'max',
      exclusive: false,
      params: { },
      message: '${path} must be less than 10% of the price',
      test: function (value) {
          // You can access the price field with `this.parent`.
          return value <= parseFloat(this.parent.price * 0.1)
      },
    }),
Run Code Online (Sandbox Code Playgroud)

这是doc
您可以在此处查看并尝试它的工作原理。

我希望这能帮到您。