gpt4 book ai didi

javascript - 是的:将字段本身与另一个字段进行比较

转载 作者:行者123 更新时间:2023-11-29 10:27:10 24 4
gpt4 key购买 nike

我有

StartIntensity: yup.number(),
EndIntensity: yup
.number()
.when(
"StartIntensity",
(StartIntensity: number, schema: any) => {
return !!StartIntensity
? schema.moreThan(
StartIntensity,
"Max should be > min"
)
: schema;
}
),

但我需要这样的东西

StartIntensity: yup.number(),
EndIntensity: yup
.number()
.when(
"StartIntensity, EndIntensity",
(StartIntensity: number, EndIntensity: number, schema: any) => {
return !!StartIntensity && StartIntensity !== EndIntensity
? schema.moreThan(
StartIntensity,
"Max should be > min"
)
: schema;
}
),

但是上面的代码不能正常工作。是否有可能通过其他方式执行此验证?

最佳答案

在你的例子中,.when() 的第一个参数应该是一个键数组:

StartIntensity: yup.number(),
EndIntensity: yup
.number()
.when(
["StartIntensity", "EndIntensity"],
(StartIntensity: number, EndIntensity: number, schema: any) => {
return !!StartIntensity && StartIntensity !== EndIntensity
? schema.moreThan(
StartIntensity,
"Max should be > min"
)
: schema;
}
),

keys: string | Array

https://github.com/jquense/yup#mixedwhenkeys-string--arraystring-builder-object--value-schema-schema-schema

如果上面的代码抛出“循环依赖”错误(我认为它会),请尝试以下代码:

StartIntensity: yup.number(),
EndIntensity: yup
.number()
.when('StartIntensity', (StartIntensity, schema) => {
return schema.test({
test: EndIntensity => !!StartIntensity && EndIntensity > StartIntensity,
message: "Max should be > min"
})
}),

或者你也可以使用ref:

StartIntensity: yup.number(),
EndIntensity: yup
.number()
.moreThan(yup.ref('StartIntensity'), "Max should be > min")

关于javascript - 是的:将字段本身与另一个字段进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56241892/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com