0

I'm trying to implement a yup validation schema and lets say I have five numeric values (A, B, C, D, E)

I want D and E be less than a math function based on A,B,C and some constant value. Something like this:

const upperBound = Math.min(A,B,C)-10;
if((D > upperBound) || (E > upperBound))
    return FAIL;
else
    return PASS;

I have reviewed many threads on SO but none of them address multiple variable dependency. Thanks.

AleX_
  • 508
  • 1
  • 6
  • 20

1 Answers1

3

You can use the test function to achieve that:

Yup.object().test({
          name: 'D and E less than ABC', // Your custom error id
          test: function () {
             const {A,B,C,D,E} = this.parent; // Access the object data, here this.parent contains your data
             const upperBound = Math.min(A,B,C)-10;
             if((D > upperBound) || (E > upperBound))
                 return this.createError({
                  message: `D and E must be below min`, // Error message for the user
                  path: `D`, // The object path where you want show the error
                });
             return true; // True for no error
        }),
Shimi
  • 1,178
  • 8
  • 18
Domino987
  • 8,475
  • 2
  • 15
  • 38
  • Thanks, can I daisy-chain tests if I want to add a lets say lower bound? – AleX_ Nov 30 '20 at 22:45
  • 1
    Yes that should work as expected, I only know that array min does not work with that, But since you are not using arrays, it should work as expected. – Domino987 Nov 30 '20 at 22:52
  • eslint throws this error `Stateless functional components should not use 'this'` on line `const { A,B,C,D } = this.parent;` . Any recommendations to fix or should I just ignore? – AleX_ Dec 01 '20 at 19:31
  • 1
    You need to use function () {}. Not arrow function with ()=>{} due to how this is handle differently between these two calls. Can you share you exact code? – Domino987 Dec 01 '20 at 20:31