最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Yup validation; can the same field accept different types? - Stack Overflow

programmeradmin0浏览0评论

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 badges
Add a ment  | 

1 Answer 1

Reset to default 9
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;
      }
    }
  })
发布评论

评论列表(0)

  1. 暂无评论