jquense / yup

Dead simple Object schema validation
MIT License
22.72k stars 925 forks source link

Use other field value in addMethod #2201

Closed drastus closed 4 months ago

drastus commented 4 months ago

I'm trying to write a custom Yup method for phone number validation. I have a separate field for phone number prefix (calling code), so I have to use it in my method.

const schema = yup.object({
  phonePrefix: yup.string().required(),
  phoneNumber: yup.string().phoneNumber(yup.ref("phonePrefix")),
});

Here is the outline of the custom method:

yup.addMethod(yup.string, "phoneNumber", function checkPhoneNumberString(prefixRef) {
  return this.test("is-valid-phone-number", "Enter valid phone number",
    (value) => {
      if (value == undefined) return true;
      const prefix = this.resolve(prefixRef);
      // `prefix` should be string, but it is Yup `StringSchema` object instead
      return isValidPhoneNumber(value, prefix);
    },
  );
});

Is there any way to dereference other fields in addMethod?

I know I can use this.parent in schema definition, but I'm using phone validation in a number of forms, so repeating the same test function over and over is not really a solution in my case.

Test case: https://codesandbox.io/p/sandbox/polished-sea-2twzhf

jquense commented 4 months ago

you are getting the wrong resolve function in your test, b/c you are using an arrow function, this in there refers the this from the checkPhoneNumberString function which is the string schema instance. Switch from an arrow function to a function expression and try again