1

I need to compare two number fields. AreaTo must be bigger than AreaFrom. It works this way:

area_to: Yup.number().min(
  Yup.ref("area_from"),
  `AreaTo should be bigger than AreaFrom`
),

The problem is I also use custom number formatting in this fields, that returns string, so the field type should be not number but string. But min() is not usable with the strings. I have a function parseNumber(str) that parse number from that string. So I need something like:

area_to: parseNumber(Yup.string()).min(
  Yup.ref("area_from"),
  `AreaTo should be bigger than AreaFrom`
),

But obviously it don’t work that way. Please help me to implement it properly.

Andrew
  • 3,825
  • 4
  • 30
  • 44
Yulia
  • 157
  • 1
  • 6
  • 1
    Does this answer your question? [Get the value of another field for validation in Yup Schema](https://stackoverflow.com/questions/63058945/get-the-value-of-another-field-for-validation-in-yup-schema) – Andrew May 25 '22 at 17:07

2 Answers2

2

I think you'd want to use test(), and pass in testContext, to reference the other field's value via testContext.parent:

const validationSchema = Yup.object().shape({ 
       area_from: Yup.number().isRequired('Required'),
       area_to: Yup.mixed().test('isLarger', 'area_to must be larger than area_from', (value, testContext) => {
             if (testContext.parent.area_from > value) return false
             return true
        })
})

You can read the documentation on this feature here.

Andrew
  • 3,825
  • 4
  • 30
  • 44
0

At the end this solution worked as expected:

area_to: Yup.string().test(
      "area_compare",
      `area_to must be bigger then area_from`,
      function (area_to: string | undefined): boolean {
        return area_to
          ? parseNumber(area_to) > parseNumber(this.parent.area_from)
          : true;
      }
    ),
Yulia
  • 157
  • 1
  • 6