I am facing a challenge in setting up a complex validation using the library yup for a model with interdependent numeric fields.
To illustrate, consider an object structured like this:
{
a: number,
b: number
}
The validation I aim to achieve is ensuring that b
is less than half of a
.
An ideal solution would look something like this conceptually:
yup.object().shape({
a: yup
.number(),
b: yup
.number()
.max(a/2) <-- DOES NOT WORK
However, the issue arises as there is no reference to a
within the scope.
Exploring the use of test
, but struggling to incorporate the entire object into the scope:
yup.object().shape({
a: yup
.number(),
b: yup
.number()
.test('test', 'b should be less than a/2', b => b < a/2) <-- DOES NOT WORK
Even considering when
for conditional validation does not provide a solution, despite its potential for handling intricate validations of related fields:
yup.object().shape({
a: yup
.number(),
b: yup
.number()
.when('a', {is: true, then: yup.number().max(a/2)}) <-- DOES NOT WORK