繁体   English   中英

使用 Yup 检查数组长度的验证 --> 如果长度 === 1 则出错

[英]Validation using Yup to check array length --> error if length === 1

我有以下 object:

{
    array: [1]
}

以及以下代码:

myArray: Yup.array().of(
    Yup.object().shape({
        name: Yup.string().max(255).required().label('Name')
    })
)

现在我检查名称是必需的,我需要检查myArray是否有length === 1以返回错误。

如果您只想测试length === 1 ,可以使用mixed.test(options: object)

myArray: array()
  .of(
    object().shape({
      name: string()
        .max(255)
        .required()
        .label("Name")
    })
  )
  .test({
    message: 'The error message if length === 1',
    test: arr => arr.length !== 1,
  })

演示:

编辑神圣的http-e3y4e

array.min(limit: number | Ref, message?: string | function)如果你想测试length === 0 | 1 length === 0 | 1

myArray: Yup.array()
  .of(
    Yup.object().shape({
      name:Yup.string()
        .max(255)
        .required()
        .label('Name')
      })
  )
  .min(2, 'The error message if length === 0 | 1')

演示:

编辑happy-sea-dds1e

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM