Dejan
Dejan

Reputation: 10343

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

Upvotes: 4

Views: 588

Answers (1)

Dejan
Dejan

Reputation: 10343

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))

Upvotes: 2

Related Questions