BeetleJuice
BeetleJuice

Reputation: 40916

Yup validation; can the same field accept different types?

I am pretty new to Yup. I'm trying to validate that a field can be either a string that follows a certain regular expression, or an array of such strings.

Here is a working example of checking the string matches my regex

{ field: yup.string().matches(regex) }

Now I want field to also be valid if it has an array of such strings:

{field: yup.array().of(yup.string().matches(regex))}

But how do I combine the two? I've tried:

{
  field: yup.mixed().when('field', {
    is: Array.isArray,
    then: yup.array().of(yup.string().matches(regex)),
    otherwise: yup.string().matches(regex)
  })
}

But I understandably get a cyclic dependency error since the field depends on itself. What's the correct syntax?

Upvotes: 9

Views: 6046

Answers (1)

ParagDineshGupta
ParagDineshGupta

Reputation: 224

yup.mixed().test('test-name', 'error-msg', (value) => {
    if (Array.isArray(value))
      for (let i = 0; i < value.length; i++) {
        if (!new RegExp('your-regx').test(value[i])) {
          return false;
        }
      }
    else {
      if (!new RegExp('your-regx').test(value)) {
        return false;
      }
    }
  })

Upvotes: 9

Related Questions