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 bine 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?
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 bine 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?
Share Improve this question asked Mar 12, 2020 at 14:32 BeetleJuiceBeetleJuice 40.9k21 gold badges118 silver badges180 bronze badges1 Answer
Reset to default 9yup.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;
}
}
})