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

我将 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。如何获取此验证中价格字段的值?


温温酱
浏览 181回答 2
2回答

慕姐8265434

number.max不能引用其他字段并在验证时用它计算。如果你想这样做,你需要使用mixed.test.这是一个例子。&nbsp; tips: number()&nbsp; &nbsp; .min(0, `Minimum tip is $0`)&nbsp; &nbsp; .test({&nbsp; &nbsp; &nbsp; name: 'max',&nbsp; &nbsp; &nbsp; exclusive: false,&nbsp; &nbsp; &nbsp; params: { },&nbsp; &nbsp; &nbsp; message: '${path} must be less than 10% of the price',&nbsp; &nbsp; &nbsp; test: function (value) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // You can access the price field with `this.parent`.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return value <= parseFloat(this.parent.price * 0.1)&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; }),这是文档。您可以在此处检查并尝试它是如何工作的。

隔江千里

如果您不想使用this.parent访问其他属性值,您可以使用context。tips: number().min(0, `Minimum tip is $0`).test(&nbsp; 'max',&nbsp; '${path} must be less than 10% of the price',&nbsp; (value, context) => value <= parseFloat(context.parent.price * 0.1),),// ORtips: number().min(0, `Minimum tip is $0`).test({&nbsp; &nbsp; &nbsp; name: 'max',&nbsp; &nbsp; &nbsp; exclusive: false,&nbsp; &nbsp; &nbsp; params: { },&nbsp; &nbsp; &nbsp; message: '${path} must be less than 10% of the price',&nbsp; &nbsp; &nbsp; test: (value, context) => value <= parseFloat(context.parent.price * 0.1),&nbsp; &nbsp; }),
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript