I had
StartIntensity: yup.number(),
EndIntensity: yup
.number()
.when(
"StartIntensity",
(StartIntensity: number, schema: any) => {
return !!StartIntensity
? schema.moreThan(
StartIntensity,
"Max should be > min"
)
: schema;
}
),
but I need something like that
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;
}
),
but code above doesn't work properly. Is there any possibility to make this work ot other ways to execute this validation?
In your case first argument of .when() should be an array of keys:
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
If the above code throws "Cyclic dependency" error (which I think it will), try the following code:
StartIntensity: yup.number(),
EndIntensity: yup
.number()
.when('StartIntensity', (StartIntensity, schema) => {
return schema.test({
test: EndIntensity => !!StartIntensity && EndIntensity > StartIntensity,
message: "Max should be > min"
})
}),
Or you can also use the ref:
StartIntensity: yup.number(),
EndIntensity: yup
.number()
.moreThan(yup.ref('StartIntensity'), "Max should be > min")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With