1
votes

I have a form with two inputs, one is a select where you choose a country, the other input is text input field which gets validation schema (EU tax regex) based on the country chosen on the select item.

I am trying to use yup for this, but am not aware how to access the value of another field in yup.

  const taxIdValidation = {
    AT: '(AT)?U[0-9]{8}',
    BE: '(BE)?0[0-9]{9}',
    BG: '(BG)?[0-9]{9,10}',
    CY: '(CY)?[0-9]{8}L',
    CZ: '(CZ)?[0-9]{8,10}',
    DE: '(DE)?[0-9]{9}',
    DK: '(DK)?[0-9]{8}',
    EE: '(EE)?[0-9]{9}',
    GR: '(EL|GR)?[0-9]{9}',
    ES: '(ES)?[0-9A-Z][0-9]{7}[0-9A-Z]',
    FI: '(FI)?[0-9]{8}',
    FR: '(FR)?[0-9A-Z]{2}[0-9]{9}',
    GB: '(GB)?([0-9]{9}([0-9]{3})?|[A-Z]{2}[0-9]{3})',
    HU: '(HU)?[0-9]{8}',
    IE: '(IE)?[0-9]S[0-9]{5}L',
    IT: '(IT)?[0-9]{11}',
    LT: '(LT)?([0-9]{9}|[0-9]{12})',
    LU: '(LU)?[0-9]{8}',
    LV: '(LV)?[0-9]{11}',
    MT: '(MT)?[0-9]{8}',
    NL: '(NL)?[0-9]{9}B[0-9]{2}',
    PL: '(PL)?[0-9]{10}',
    PT: '(PT)?[0-9]{9}',
    RO: '(RO)?[0-9]{2,10}',
    SE: '(SE)?[0-9]{12}',
    SI: '(SI)?[0-9]{8}',
    SK: '(SK)?[0-9]{10}'
  };

  const validationSchema = yup.object().shape({
      taxIdentificationNumbers: yup
      .array()
      .of(
        yup.object().shape({
          country: yup.string().nullable(),
          vatValue: yup
            .string()
            .nullable()
            .when('country', {
              is: value => value && value.length > 0,
              then: yup
                .string()
                .matches(taxIdValidation[value])
                .required('Tax ID is required.')
            })
        })
      )
      .nullable()
  });

I have a taxIdValidation object, and then based on the value of the country alphaCode2, I would like to set the regex to that same key. However, in this syntax, I cannot access countries value.

If anyone has an idea how to approach this problem, I'd be very happy to hear.

1

1 Answers

1
votes

You can use test instead, to get parent or sibling values:

const validationSchema = yup.object().shape({
      taxIdentificationNumbers: yup
      .array()
      .of(
        yup.object().shape({
          country: yup.string().nullable(),
          vatValue: yup
            .string()
            .nullable()
            .when('country', {
              is: value => value && value.length > 0,
              then: yup
                .string()
                .test('tax validation', 'Wrong tax format', function (value) {
                   const { country } = this.parent;
                   return value.match(taxIdValidation[country]);
                 })
                .required('Tax ID is required.')
            })
        })
      )
      .nullable()
  });