0

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.

This is really similar to this question but our approaches are totally different since I also need to handle countries outside EU.

MrRaknum
  • 5
  • 3

1 Answers1

0

Ok, so apparently I was missing some possible functions that work here!

Here is my solution:

Yup.string().when("countryCode", {
    is: value => {
      const country = getCountryBy.code(value);
      return country?.EU;
    },
    then: validateAgainstRegexps(getEuCountries.regex()),
    otherwise: Yup.string()
      .trim()
      .min(genericTaxIdMinLength, t("validation.minLength", { minLength: genericTaxIdMinLength }))
      .required(t("validation.required"))
  });

All I needed to do was to add the logic within .when() as stated here: is: (value) => value == true which I thought it only admitted equalities (===).

MrRaknum
  • 5
  • 3