【问题标题】:Get the value of another field for validation in Yup Schema在 Yup Schema 中获取另一个字段的值进行验证
【发布时间】:2020-11-13 10:57:07
【问题描述】:

我正在使用 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.");

然而这并不能编译,因为 yup.ref 返回一个 Ref。如何获取此验证中价格字段的值?

【问题讨论】:

  • yup.reach('price') 有帮助吗?从我读到的here,您可以使用reach访问对象模式

标签: javascript formik yup


【解决方案1】:

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)
      },
    }),

这里是doc
您可以检查并尝试它是如何工作的here

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2016-08-01
    • 2021-10-20
    • 2021-01-19
    • 2019-04-17
    • 2021-06-27
    • 2020-05-10
    • 2020-11-19
    • 2021-11-01
    • 2013-09-10
    相关资源
    最近更新 更多