为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

温温酱 2022-12-02 16:27:57
我将 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。如何获取此验证中价格字段的值?
查看完整描述

2 回答

?
慕姐8265434

TA贡献1813条经验 获得超2个赞

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)

      },

    }),

这是文档您可以在此处

检查并尝试它是如何工作的。


查看完整回答
反对 回复 2022-12-02
?
隔江千里

TA贡献1906条经验 获得超10个赞

如果您不想使用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),

    }),


查看完整回答
反对 回复 2022-12-02
  • 2 回答
  • 0 关注
  • 180 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号