簡體   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