Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate interdependent numeric fields using Yup?

I have a model with interdependent numeric fields and I'm struggling to see how to setup a complex validation using yup.

For the sake of simplicity, imagine an object having the following shape:

{
    a: number,
    b: number
}

I would like to validate that b is less then half of a.

So conceptually what I would want is something like this:

yup.object().shape({
    a: yup
        .number(),
    b: yup
        .number()
        .max(a/2) <-- DOES NOT WORK

Of course, this does not work since there is no a in scope there.

Using test, I don't see how to get the whole object into 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

And using when (conditional validation) also doesn't seem to help although it seems to be used for complex validation of interdependent fields:

yup.object().shape({
    a: yup
        .number(),
    b: yup
        .number()
        .when('a', {is: true, then: yup.number().max(a/2)}) <-- DOES NOT WORK
like image 557
Dejan Avatar asked Oct 19 '25 20:10

Dejan


1 Answers

It seems that there are other overloads of when that pass on the value of the tested field:

yup.object().shape({
a: yup
    .number(),
b: yup
    .number()
    .when('a', (a, schema) => return schema.max(a/2))
like image 119
Dejan Avatar answered Oct 21 '25 10:10

Dejan