jquense / yup

Dead simple Object schema validation
MIT License
22.88k stars 933 forks source link

Validation with two related fields with variable regex test #1563

Closed miguelgonch closed 2 years ago

miguelgonch commented 2 years ago

So I have a world wide list of countries and I want to validate the VAT / Tax Number for countries from the EU.

Here is an example for the countries array:

  {
    name: "Belarus",
    dialCode: "+375",
    code: "BY"
  },
  {
    name: "Belgium",
    dialCode: "+32",
    code: "BE",
    EU: true,
    vatPrefix: "BE",
    regex: `0[0-9]{9}`
  },
...

I have my countries and tax number fields, but so far I can't manage to differentiate if a country is from EU or not. Here is my validation code (not working):

 return Yup.string().when("???", {
    is: "EU",
    then: schema.test("regexPattern", t("validation.invalidValue"), (value: unknown) =>
    regexPattern.test(String(value))
  ),
    otherwise: Yup.string()
    .trim()
    .min(5, t("validation.minLength", { minLength: 5}))
    .required(t("validation.required"));
  });

I was trying to get the countryCode from the countryField and with that make the query to the countries array and if it has a regex then pass the variable to the regex validation. But I have no idea how to do it.

Help Others Reproduce

I have nothing to run 🥲

miguelgonch commented 2 years ago

https://stackoverflow.com/questions/70791846/validation-with-two-related-fields-with-variable-regex-test